IC100 Day 3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Introduction to Programming:

Day 3
Soumajit Pramanik
What does “Type” Mean?
• In Python variables, literals, and
constants have a “type”
>>> ddd = 1 + 4
• Python knows the difference >>> print(ddd)
between an integer number and a 5
string >>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
• For example “+” means “addition”
if something is a number and
“concatenate” if something is a concatenate = put together
string
Type Matters >>> eee = 'hello ' + 'there'
>>> eee = eee + 1
• Python knows what “type” Traceback (most recent call last):
everything is File "<stdin>", line 1, in <module>
TypeError: can only concatenate str
• Some operations are prohibited (not "int") to str
>>> type(eee) 5 Types
<class 'str'>
• You cannot “add 1” to a string >>> type('hello') Numbers
<class 'str'> Strings
>>> type(1)
• We can ask Python what type <class 'int'>
List
Tuple
something is by using the type() >>> Dictionary
function.
Several Types of Numbers
>>> xx = 1
● Numbers have two main types - integers and
>>> type (xx)
float <class 'int'>
● Integers are whole numbers: -14, -2, 0, 1, 100, >>> temp = 98.6
401233 >>> type(temp)
● Floating Point Numbers have decimal parts: <class 'float'>
-2.5, 0.0, 98.6, 14.0 >>> type(1)
● There is another number type - complex <class 'int'>
>>> type(1.0)
● No ‘long’ type in Python3
<class 'float'>
>>>
Strings
• Strings in Python are identified as a contiguous set of
characters in between 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.
Example
• str = 'Hello World!'

• print(str) # Prints complete string


• print(str[0]) # Prints first character of the
string
• print(str[2:5]) # Prints characters starting from
3rd to 5th
• print(str[2:]) # Prints string starting from 3rd
character
• print(str * 2) # Prints string two times
• print(str + "TEST") # Prints concatenated string
Example: Result
• Hello World!
• H
• llo
• llo World!
• Hello World!Hello World!
• Hello World!TEST
Type Conversions >>> print(float(99) / 100)
0.99
>>> i = 42
>>> type(i)
• When you put an integer and <class 'int'>
floating point in an expression >>> f = float(i)
the integer is implicitly >>> print(f)
converted to a float 42.0
>>> type(f)
<class 'float'>
• You can control this with the >>> print(1 + 2 * float(3) / 4 - 5)
built in functions int() and float() -2.5
>>>
>>> sval = '123'
String >>> type(sval)
<class 'str'>

Conversions >>> print(sval + 1)


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to
• You can also use int() and str
>>> ival = int(sval)
float() to convert between >>> type(ival)
strings and integers <class 'int'>
>>> print(ival + 1)
124
• You will get an error if the >>> nsv = 'hello bob'
string does not contain >>> niv = int(nsv)
numeric characters Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10 :
’hello bob’
User Input

• We can instruct Python to


pause and read data from nam = input(‘Who are you?’)
the user using the print('Welcome', nam)
raw_input (Python 2) or Eg.
input (Python 3) function Who are you? Chuck
Welcome Chuck
• It returns a string.
Converting User Input

• If we want to read a inp = input(‘Europe floor?’)


number from the user, we usf = int(inp) + 1
must convert it from a print('US floor', usf)
string to a number using a
type conversion function
Europe floor? 0
US floor 1
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of code
• Document who wrote the code or other ancillary information
• Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = raw_input('Enter file:')
handle = open(name, 'r')
text = handle.read()
words = text.split()

# Count word frequency


‘’’counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1’’’

# Find the most common word


bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count

# All done
print bigword, bigcount
Mnemonic Variable Names
• Since we programmers are given a choice in how we choose
our variable names, there is a bit of “best practice”

• We name variables to help us remember what we intend to


store in them (“mnemonic” = “memory aid”)

• This can confuse beginning students because well named


variables often “sound” so good that they must be keywords

http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c=a*b
print x1q3p9afd print(c)

hours = 35.0
What is this rate = 12.50
code doing? pay = hours * rate
print pay
Python Arithmetic Operators:
Let, a=10 and b=20
Operator Description Example
+ Addition - Adds values on either side of the a + b will give 30
operator
- Subtraction - Subtracts right hand operand a - b will give -10
from left hand operand
* Multiplication - Multiplies values on either side a * b will give 200
of the operator
/ Division - Divides left hand operand by right b / a will give 2
hand operand
% Modulus - Divides left hand operand by right b % a will give 0
hand operand and returns remainder
** Exponent - Performs exponential (power) a**b will give 10 to the
calculation on operators power 20
// Floor Division - The division of operands 9//2 is equal to 4 and
where the result is the quotient in which the 9.0//2.0 is equal to 4.0
digits after the decimal point are removed.
Python Comparison Operators:
Let, a=10 and b=20
Operato
Description Example
r
== Checks if the value of two operands are equal or not, (a == b) is not true.
if yes then condition becomes true.
!= Checks if the value of two operands are equal or not, (a != b) is true.
if values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the (a > b) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (a < b) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (a >= b) is not true.
equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or (a <= b) is true.
equal to the value of right operand, if yes then
condition becomes true.
Python Assignment Operators:
Operator Description Example
= Simple assignment operator, Assigns values from right c = a + b will assign
side operands to left side operand value of a + b into c
+= Add AND assignment operator, It adds right operand to c += a is equivalent
the left operand and assign the result to left operand to c = c + a
-= Subtract AND assignment operator, It subtracts right c -= a is equivalent
operand from the left operand and assign the result to left to c = c - a
operand
*= Multiply AND assignment operator, It multiplies right c *= a is equivalent
operand with the left operand and assign the result to left to c = c * a
operand
/= Divide AND assignment operator, It divides left operand c /= a is equivalent
with the right operand and assign the result to left to c = c / a
operand
%= Modulus AND assignment operator, It takes modulus c %= a is equivalent
using two operands and assign the result to left operand to c = c % a
**= Exponent AND assignment operator, Performs exponential c **= a is equivalent
(power) calculation on operators and assign value to the to c = c ** a
left operand
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
multiple objects to multiple 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, and one string object with the value "john" is assigned to the
variable c.
• a, b, c = 1, "john“# WHAT HAPPENS HERE?
Python Bitwise Operators:
Operato
Description Example
r
& Binary AND Operator copies a bit to the result (a & b) will give 12 which
if it exists in both operands. is 0000 1100
| Binary OR Operator copies a bit if it exists in (a | b) will give 61 which
either operand. is 0011 1101
^ Binary XOR Operator copies the bit if it is set (a ^ b) will give 49 which
in one operand but not both. is 0011 0001
~ Binary Ones Complement Operator is unary (~a ) will give -61 which
and has the effect of 'flipping' bits. is 1100 0011
<< Binary Left Shift Operator. The left operands a << 2 will give 240
value is moved left by the number of bits which is 1111 0000
specified by the right operand.
>> Binary Right Shift Operator. The left operands a >> 2 will give 15 which
value is moved right by the number of bits is 0000 1111
specified by the right operand.
Example - Bitwise Operators
a = 60 = 0011 1100

b = 13 = 0000 1101

a & b = 0000 1100 = 12

a | b = 0011 1101 = 61

a ^ b = 0011 0001 = 49

~a = 1100 0011 = -61

a<<2 = 1111 0000 = 240

a>>2 = 0000 1111 = 15


Python Logical Operators:
Operat
Description Example
or
and Called Logical AND operator. If both the (a and b) is true.
operands are true then then condition becomes
true.
or Called Logical OR Operator. If any of the two (a or b) is true.
operands are non zero then then condition
becomes true.
not Called Logical NOT Operator. Use to reverses not(a and b) is false.
the logical state of its operand. If a condition is
true then Logical NOT operator will make false.
Python Membership Operators
In addition to the operators discussed previously, Python has
membership operators, which test for membership in a
sequence, such as strings, lists, or tuples.

Operator Description Example


in Evaluates to true if it finds a variable in the x in y, here in results in
specified sequence and false otherwise. true if x is a member of
sequence y.
not in Evaluates to true if it does not finds a x not in y, here not in
variable in the specified sequence and false results in a true if x is not
otherwise. a member of sequence y.

“Cap” in “Captain” → true


Python Operators Precedence
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators

You might also like