Basic: Concepts

More Basic Concepts

Dynamic Typing: in shell

>>>  x = input("enter a number ")
>>> enter a number 56
>>> print ("x ", type(x))
>>> x = 76
>>> print ("x ", type(x))
x  
>>> x = "HI"
>>> print ("x ", type(x))
x  

>>> 
Question: 
x = input("enter a number ")
How can you convert x to an integer?

Floating-point type

3**5
243
5//2   # truncates the decimal part
2
5.0/2
2.5
x = 5
x/2
2.5
x = float(x)
x/2
2.5

Arithmetic Operators

arithmeticOps

Question: Can you guess what the modulus operator does?

5%2
1
25%3
1
55%6
1
48%6
0
8%3
2
8%5
3

Rules of operator precedence:

opPrecedenceTable

 

pythonExpression1

Question: What would happen if you omit the parentheses?

pythonExpression2

Expression with the modulus operator:

modulusExpression

Question: What would the value of z be if
p = 10
r = 2
q = 7
w = 5
x = 2
y = 1

Let’s trace the following expression:

order1

when
a = 2
x = 5
b = 3
c = 7

order2

Class work and homework:

Screen Shot 2013-09-17 at 11.27.04 PM

Trace the following expressions

a) x = 7 + 3 * 6 / 2 – 1

b) x = 2 % 2 + 2 * 2 – 2 /2

c) x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) )

Programming Assignments:

1. Write a program, AlgeCalculator_YI.py that requests the user to enter two numbers and prints with a user-friendly message the sum, product, difference, and quotient of the two numbers.