0% found this document useful (0 votes)
101 views

1 - Variable, Data Types and Operators

CS141 is an introduction to computing course that teaches Python programming language. Python is a cross-platform, open source language that can be run on Windows, Mac OS, and Linux. It has various modes like immediate mode, script mode, and IDE mode. The document discusses Python comments, variables, data types, operators, and basic input/output using print functions. Key concepts covered are Python syntax, identifiers, keywords, assigning values, and multiple assignments.

Uploaded by

Hamza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

1 - Variable, Data Types and Operators

CS141 is an introduction to computing course that teaches Python programming language. Python is a cross-platform, open source language that can be run on Windows, Mac OS, and Linux. It has various modes like immediate mode, script mode, and IDE mode. The document discusses Python comments, variables, data types, operators, and basic input/output using print functions. Key concepts covered are Python syntax, identifiers, keywords, assigning values, and multiple assignments.

Uploaded by

Hamza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

• Course

• CS141: Introduction to Computing


• Python Language

• Reference
• https://www.tutorialspoint.com/python/python_variable_types.htm
• https://www.tutorialspoint.com/python/python_basic_operators.htm
Humans have five basic
senses: sight, hearing,smell, taste and touch. Humans have five
basic senses: touch, sight, hearing, smell and taste. The sensing
organs associated with each sense send information to the brain to
help us understand and perceive the world around us.
• If I ask you to add 2+5
What will happen?
Your brain will add these two numbers and
this addition is in response to my instruction.
you will output the result either by speaking
or by writing.
• Identify the organs for sending input to brain
and output the result
• organs through which information goes to brain
are hands,eyes,mouth,ears,nose
• for output you may use your hands or mouth
Block diagram of a Computer
• If I instruct you to carry out some task then your
brain will work accordingly and you will
communicate the result.
• These set of instructions can be called as
program.
• You may understand various languages and give
response according to the language statements.
• Similarly various languages are used in your
computer to give instructions and these set of
instructions are called as program.
• What is Python?
• Python is a cross-platform programming
language, meaning, it runs on multiple platforms
like Windows, Mac OS , Linux.
• It is free and open source.
• Even though most of today’s Linux and Mac have
Python preinstalled in it, the version might be
out-of-date. So, it is always a good idea to install
the most current version. You can download the
latest version of Python and install it.
• For example you can down load IDLE 2.7
Python/IDLE 3.7 Python via the internet.
• Various inter
• Now there are various ways to start Python.
• 1. Immediate mode
• Instruction results are observed after the
execution of each instruction
• Click IDLE (python 3.7 32 bit) icon and you
observe the shell of immediate mode. We can
directly type in Python expressions and press
enter to get the output.
• >>>
• is the Python prompt. It tells us that the
interpreter is ready for our input. Try typing in
1 + 1 and press enter. We get 2 as the output.
• 2. Script mode
• This mode is used to execute Python program
written in a file. Such a file is called a script.
Scripts can be saved to disk for future use.
Python scripts have the extension .py,
meaning that the filename ends with .py.
• For example: helloWorld.py
• To execute this file in script mode we will use
simply run command and execution will take
place after saving the file/script.
• 3. Integrated Development Environment (IDE)
• We can use any text editing software to write a Python
script file. We just need to save it with
the .py extension.
• But using an IDE can make our life a lot easier. IDE is a
piece of software that provides useful features like
code hinting, syntax highlighting and checking, file
explorers etc. to the programmer for application
development.
• Using an IDE can get rid of redundant tasks and
significantly decrease the time required for application
development.
• IDLE 2.7 Python/IDLE 3.7 Python is a graphical user
interface (GUI) that can be installed and is available
from the official website.
• We can also use other commercial or free IDE
according to our preference.
• Python Comments
• Comments are very important while writing a program. It describes what's
going on inside a program so that a person looking at the source code does
not have a hard time figuring it out. You might forget the key details of the
program you just wrote in a month's time. So taking time to explain these
concepts in form of comments is always fruitful.
• In Python, we use the hash (#) symbol to start writing a comment.
• It extends up to the newline character. Comments are for programmers for
better understanding of a program. Python Interpreter ignores comment.
• #This is a comment
• #print out Hello
• print('Hello')
• Multi-line comments
• If we have comments that extend multiple lines, one way of doing it is to use
hash (#) in the beginning of each line. For example:
• #This is a long comment
• #and it extends
• #to multiple lines
• Another way of doing this is to use triple quotes, either ''' or """.
• These triple quotes are generally used for multi-line strings. But they can be
used as multi-line comment as well. Unless they are not docstrings, they do
not generate any extra code.
• """This is also a
• perfect example of
• multi-line comments"""
Python - Variable Types And Use of Operators
• Variables are reserved memory locations
to store values.
• This means that when you create a variable
you reserve some space in memory.
• Based on the data type of a variable, the
interpreter allocates memory and decides
what can be stored in the reserved memory.
• By assigning different data types to
variables, you can store integers, decimals or
characters in these variables.
Python Identifiers
Rules for writing identifiers
• Identifier is the name given to entities like class, functions,
variables etc. in Python. It helps differentiating one entity
from another.

• Rules for writing identifiers


• Identifiers can be a combination of letters in lowercase (a to z)
or uppercase (A to Z) or digits (0 to 9) or an underscore
(_). Names like myClass, var_1 and print_this_to_screen, all
are valid example.
• An identifier cannot start with a digit. 1variable is invalid,
but variable1 is perfectly fine.
• Keywords cannot be used as identifiers We cannot use special
symbols like !, @, #, $, % etc. in our identifier.
• Identifier can be of any length
Things to care about
• Python is a case-sensitive language. This
means, Variable and variable are not the same.
Always name identifiers that make sense.
• While, c = 10 is valid. Writing count = 10 would make
more sense and it would be easier to figure out what
it does even when you look at your code after a long
gap.
• Multiple words can be separated using an
underscore, this_is_a_long_variable.
• We can also use camel-case style of writing, i.e.,
capitalize every first letter of the word except the
initial word without any spaces. For
example: camelCaseExample
Python Keywords
• Keywords are the reserved words in Python.
• We cannot use a keyword as variable
name, function name or any other identifier. They
are used to define the syntax and structure of the
Python language.
• In Python, keywords are case sensitive.
• There are 33 keywords in Python 3.3. This number
can vary slightly in course of time.
• All the keywords except True, False and None are in
lowercase and they must be written as it is.
Keywords in Python programming language cannot be
used as identifier

• False class finally is return


• None continue for lambda try
• True def from nonlocal while
• and del global not with
• as elif if or yield
• assert else import pass
• break except in raise
• Assigning Values to Variables
• Python variables do not need explicit
declaration to reserve memory space.
• The declaration happens automatically when
you assign a value to a variable.
• The equal sign (=) is used to assign values to
variables. The operand to the left of the =
operator is the name of the variable and the
operand to the right of the = operator is the
value stored in the variable.
• Python Output Using print() function
• We use the print() function to output data to the
standard output device (screen).
Example:1
print('This sentence is output to the screen')
# Output: This sentence is output to the screen
a=5
print('The value of a is', a)
# Output: The value of a is 5
• Example:2
• counter = 100 # An integer assignment
• miles = 1000.0 # A floating point
• name = "John" # A string
• print (counter)
• print (miles)
• print (name)

• This produces the following result −


• 100
• 1000.0
• John
• Example:3
• print ("This program is a demo of variables.")
• v=1
• print ("The value of v is now", v)
• v=v+1
• print ("v now equals itself plus one, making it worth", v)
• v = 51
• print("v can store any numerical value, to be used elsewhere.")
• print("For example, in a sentence. v is now worth", v)
• print ("v times 5 equals", v*5)
• print ("But v still only remains", v)
• print("To make v five times bigger, you would have to type v = v*5")
• v=v*5
• print ("There you go, now v equals", v, "and not", v/5)
• 2.2 Multiple Assignment
• Python allows you to assign a single value to several variables
simultaneously. For example −
a=b=c=1
• Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location. You can also
assign mulQple objects to mulQple variables. For example −
a,b,c = 1,2,"john"
• Here, two integer objects with values 1 and 2 are assigned to
variables a and b respectively, and one string object with the value
"john" is assigned to the variable c.

• Example:4
• a,b,c = 1,2,"john"
• print (a)
• print (b)
• print (c)
• Variables and Assignment
• Variables provide a way to associate names with objects. Consider
the code

• Example 5:
• pi = 3
• radius = 11
• area = pi * (radius**2)
• print (area)

• It first binds the names pi and radius to different objects of type int.
• It then binds the name area to a third object of type int.
• Apt choice of variable names plays an important role in enhancing
• readability.
In Example 6 in first line a and pi, in next line b and
diameter and in third c and area are written in
one line
Example:6
• a = 3.14159 ; pi = 3.14159
• b = 11.2 ; diameter = 11.2
• c = a*(b**2) ; area = pi*(diameter**2)
• print (area)
• print (c)
• Python allows multiple assignment. The statement
• x, y = 2, 3
• binds x to 2 and y to 3. All of the expressions on the
right-hand side of the assignment are evaluated
before any bindings are changed.
example.7
• x, y = 2, 3
• x, y = y, x
• print ('x =', x)
• print ('y =', y)
will print
x=3
y=2
Example:8
print(1,2,3,4)
# Output: 1 2 3 4
print(1,2,3,4,sep='*')
# Output: 1*2*3*4
print(1,2,3,4,sep='#')
# Output: 1#2#3#4
• Output formatting
• Sometimes we would like to format our output to make it look
attractive. This can be done by using the str.format() method. This
method is visible to any string object.
• >>> x = 5; y = 10
• >>> print('The value of x is {} and y is {}'.format(x,y))

• The value of x is 5 and y is 10Here the curly braces {} are used as


placeholders. We can specify the order in which it is printed by
using numbers (tuple index).
• Example 09
• x = 5; y = 10
• print('The value of x is {} and y is {}'.format(x,y))

• print('I love {0} and {1}'.format('bread','butter'))


• # Output: I love bread and butter
• print('I love {1} and {0}'.format('bread','butter'))
• # Output: I love butter and bread
print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name =
'John'))
Output:
Hello John, Goodmorning

x = 12.3456789

print('The value of x is %3.2f' %x)


The value of x is 12.35

print('The value of x is %3.4f' %x)


The value of x is 12.3457
Standard Data Types
• Python has various standard data types that are used to
define the operations possible on them and the storage
method for each of them. Python has five standard data
types −
• Numbers
• String
• List
• Tuple
• Dictionary

• Python Numbers
• Number data types store numeric values. Number objects
are created when you assign a value to them. For example
• var1 = 1
• var2 = 10
• You can delete a single object or multiple objects by
using the del statement. For example −
del var
del var_a, var_b
• Python supports four different numerical types –
i- int (signed integers)
ii- long (long integers, they can also be
represented
in octal and hexadecimal)
iii- float (floating point real values)
iv- complex (complex numbers)
• Integers and floating points are separated by
the presence or absence of a decimal point. 5
is integer whereas 5.0 is a floating point
number.
• Complex numbers are written in the form, x +
yj, where x is the real part and y is the
imaginary part.
• We can use the type() function to know which
class a variable or a value belongs to and is
instance() function to check if it belongs to a
particular class.
• Example 10

• a=5
• # Output: <class 'int'>
• print(type(a))
• # Output: <class 'float'>
• print(type(5.0))
• # Output: (8+3j)
• c = 5 + 3j
• print(c + 3)
• # Output: True
• print(isinstance(c, complex))

• While integers can be of any length, a floating point number is


accurate only up to 15 decimal places (the 16th place is inaccurate).
• Numbers we deal with everyday are decimal
(base 10) number system. But computer
programmers (generally embedded programmer)
need to work with binary (base 2), hexadecimal
(base 16) and octal (base 8) number systems.
• In Python, we can represent these numbers by
appropriately placing a prefix before that number.
Following table lists these prefix.
• Number system prefix for Python numbers
• Number System Prefix
• Binary '0b' or '0B'
• Octal '0o' or '0O'
• Hexadecimal '0x' or '0X‘
• Example: 11

• # Output: 107
• print(0b1101011)
• # Output: 253 (251 + 2)
• print(0xFB + 0b10)
• # Output: 13
• print(0o15)

• When you run the program, the output will be:


• 107
• 253
• 13
Examples
• int 10, 100, -786, 080, -0490, -0x260,
0x69
• long 51924361, -0x19323, 0122
0xDEFECBDAECBFBAEl, 535633629843
-052318172735, -4721885298529
• float 0.0, 15.20, -21.9, 32.3+e18, -90.
-32.54e100, 70.2-E12
• complex 3.14j, 45.j, 9.322e-36j, .876j,
-.6545+0J, 3e+26J, 4.53e-7j
• Example 12
• a = 10
• b = 20
• a1= 51924361
• b1= -4721885298529
• a2= +32.54e20
• b2= -30.54e20
• a3= -.6545+0J
• b3= .6545+10J

• print ("Results of addition")


• print (a + b)
• print (a1+b1)
• print (a2+b2)
• print (a3+b3)
• print ("Results of multiplication")
• print (a * b)
• print (a1 * b1)
• print (a2 * b2)
• print (a3 * b3)
• Types of Operator
• Python language supports the following types
of operators.
1- Arithmetic Operators
2- Comparison (Relational) Operators
3- Assignment Operators
4- Logical Operators
5- Bitwise Operators
6- Membership Operators
7- Identity Operators
• Python Arithmetic Operators
• Assume variable a holds 10 and variable b holds 20, then −
• Operator Description
Example
• + Addition Adds values on either side of the operator.
• Ex: a + b = 30
• - Subtraction Subtracts right hand operand from left hand
• operand. Example a – b = -10
• * Multiplication Multiplies values on either side of the operator
Example: a * b = 200
• / Division Divides left hand operand by right hand operand
Example: b / a = 2
• % Modulus Divides left hand operand by right hand operand
• and returns remainder Example: b % a = 0
• ** Exponent Performs exponential (power) calculation
on operators Example: a**b =10 to the power 20
Use of objects and operatprs
• i+j is the sum of i and j. If i and j are both of type
int, the result is an int.If either of them is a float,
the result is a float.
• i–j is i minus j. If i and j are both of type int, the
result is an int.If either of them is a float, the
result is a float.
• i*j is the product of i and j. If i and j are both of
type int, the result is an int. If either of them is a
float, the result is a float.
• i//j is integer division. For example, the value of
6//2 is the int 3 and the value of 6//4 is the int 1.
The value is 1 because integer division returns the
quotient and ignores the remainder.
cont;
• i/j is i divided by j. In Python 2.7, when i and j are
both of type int, the result is also an int,
otherwise the result is a float. In this book, we
will never use / to divide one int by another. We
will use // to do that. (In Python 3, the / operator,
thank goodness, always returns a float. For
example, in Python 3 the value of 6/4 is 1.5.)
• i%j is the remainder when the int i is divided by
the int j. It is typically pronounced “i mod j,”
which is short for “i modulo j.”
• i**j is i raised to the power j. If i and j are both of
type int, the result is an int. If either of them is a
float, the result is a float.
Comparison Operators
• The comparison operators are == (equal), != (not
equal),
• > (greater), >= (at least), < (less) and <= (at most).
a= 8
b=2
print a==b
print a!=b
print (a > b)
• Output will be
False
True
True
Python Logical Operators
• There are following logical operators supported by Python
language.
• There are following logical operators supported by Python
language. Assume variable a holds 10 and variable b holds
20 then −
• Operator Description & Examples
• and Logical AND If both the operands are true then
• condition becomes true.
• Example: (a and b) is true.
• or Logical OR If any of the two operands are non-zero
• then condition becomes true.
• Example: (a or b) is true.
• not Logical NOT Used to reverse the logical state of its
• operand.
Example : Not(a and b) is false.
Example:13

a=10
b=20
c=a<b
d=a!=b
f=a>b

print (c and d)
print (c or d)
print (c and f)

Output is:
True
True
False
Python Bitwise Operators
• Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows −
• a = 0011 1100
• b = 0000 1101
• There are following Bitwise operators supported by Python language
Operator Description & Example
• & Binary AND Operator copies a bit to the result if it exists in both operands
Example : (a & b) (means 0000 1100)
• | Binary OR It copies a bit if it exists in either operand.
• Exmple: (a | b) = 61 (means 0011 1101)
• ^ Binary XOR It copies the bit if it is set in one operand but not both.
Example: (a ^ b) = 49 (means 0011 0001)
• ~ Binary Ones Complement It is unary and has the effect of 'flipping' bits.
Example:(~a ) = -61 (means 1100 0011 in 2's complement form due to a
signed binary number.
• << Binary Left Shift The left operands value is moved left by the number of bits specified
by the right operand. Example : a << 2 = 240 (means 1111 0000)
• >> Binary Right Shift The left operands value is moved right by the number of bits specified
by the right operand. Example: a >> 2 = 15 (means 0000 1111)
Example 14
a = 60
b = 13
print (a&b)
print (a|b)
print (a^b)
print (~a)
Output is :
12
61
49
-61
Example 15
a = 0b1101
b = 0b1001
print (bin(a&b))
print (bin(a|b))
print (bin(a^b))
print (bin(~a))
Output is:
0b1001
0b1101
0b100
-0b1110
Python Comparison Operators
These operators compare the values on either sides of them and decide the
relation among them. They are also called Relational operators.

• Assume variable a holds 10 and variable b holds 20, then −


• Operator Description
• == If the values of two operands are equal, then the condition
becomes true. Example: (a == b) is not true.
• != If values of two operands are not equal, then condition
becomes true. Example: (a != b) is true.
• <> If values of two operands are not equal, then condition
becomes true. Example: (a <> b) is true. This is similar to !=. operator
• > If the value of left operand is greater than the value of right
operand, then condition becomes true. Example (a > b) is not true.
• < If the value of left operand is less than the value of right
operand, then condition becomes true. (a < b) is true.
• >= If the value of left operand is greater than or equal to the
value of right operand, then condition becomes true.
Example: (a >= b) is not true.
• <= If the value of left operand is less than or equal to the value
of right operand, then condition becomes true.
Example: (a <= b) is true.
• Python Assignment Operators

• Assume variable a holds 10 and variable b holds 20, then −
Operator Description
• = Assigns values from right side operands to left side operand
Example: c = a + b assigns value of a + b into c
• += It adds right operand to the left operand and assign the result to left
operand Expample: c += a is equivalent to c = c + a
• -= It subtracts right operand from the left operand and assign
the result to left operand Example: c -= a is equivalent to c = c - a
• *= It multiplies right operand with the left operand and assign
the result to left operand Example: c *= a is equivalent to c = c * a
• /= It divides left operand with the right operand and assign the
result to left operand Example: c /= a is equivalent to c = c / a
• %= It takes modulus using two operands and assign the result
to left operand Example: c %= a is equivalent to c = c % a
• **= Performs exponential (power) calculation on operators and
assign value to the left operand
Example: c **= a is equivalent to c = c ** a
• //= It performs floor division on operators and assign value to
the left operand Example: c //= a is equivalent to c = c // a
• Python Operators Precedence

The following table lists all operators from highest precedence to


lowest.
• Sr.No. Operator & Description
• 1 ** Exponentiation (raise to the power)
• 2 ~+- Complement, unary plus and minus
• 3 * / % // Multiply, divide, modulo and floor
division
• 4 +- Addition and subtraction
• 5 >> << Right and left bitwise shift
• 6 & Bitwise 'AND'
• 7 ^| Bitwise exclusive `OR' and regular
`OR'
• 8 <= < > >= Comparison operators
• 9 <> == != Equality operators
• 10 = %= /= //= -= += *= **= Assignment operators
• 11 is is not Identity operators
• 12 in not in Membership operators
• 13 not or and Logical operators
• 6 Python Strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
• Python allows for either pairs of single or double quotes. Subsets
of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
• The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator. For example –
• Example : 16
#Giving variables text, and adding text.
word1 = "Good"
word2 = "morning"
word3 = "to you too!"
print(word1, word2)
sentence = word1 + " " + word2 + " " + word3
print(sentence)
print("Sammy" + "Shark")
• The output is:
('Good', 'morning')
Good morning to you too
SammyShark
• Multi-line statement
• In Python, end of a statement is marked by a newline character. But we
can make a statement extend over multiple lines with the line
continuation character (\). For example:
• a=1+2+3+\
• 4+5+6+\
7+8+9
• This is explicit line continuation. In Python, line continuation is implied
inside parentheses ( ), brackets [ ] and braces { }. For instance, we can
implement the above multi-line statement as
• a = (1 + 2 + 3 +
• 4+5+6+
• 7 + 8 + 9)
• Here, the surrounding parentheses ( ) do the line continuation implicitly.
Same is the case with [ ] and { }. For example:
• colors = ['red',
• 'blue',
• 'green']
• We could also put multiple statements in a single line using semicolons, as
follows
• a = 1; b = 2; c = 3
• Following data types will be discussed later on
• List
• Tuples
• Dictionary
• Following operators shall be discussed later on
Membership Operators
Identity Operators

You might also like