02 Python - Getting Started
02 Python - Getting Started
Tushar B. Kute,
http://tusharkute.com
First Python program
>>> num1 = 45
>>> num2 = 56
>>> print(num1)
45
>>> num3 = 12.33
>>> print(num3)
12.33
>>> name = 'Tushar'
>>> print(name)
Tushar
Data types
• Numbers: • List
– int • Tuple
– float • Set
– complex
• Dictionary
• String
• Boolean
Integers
>>> num = 23
>>> type(num)
<class 'int'>
>>> num + 10
33
>>> num ** 100
148861915063630393937915565865597542319
871196538013686865769882092224332785393
313521523901432773468042334765921794473
10859520222529876001
•
Integer length
• Try this:
>>> num ** 1000
• This will generate a big number with 100s of
digits.
• There is NO inherent limit to the integer to
store in memory. It goes on using until we run
out of memory.
Floating point numbers
\n New Line
\t Tab
\v Vertical tab
\r Carriage Return
\b Backspace
\a Audio bell
\\ Single slash
Using escape sequences
>>> print('Hello\nWorld')
Hello
World
>>> print('Hello\bWorld')
HellWorld
>>> print('Hello\vWorld')
Hello
World
>>> print('Hello\rWorld')
World
>>> print('Hello\\World')
Hello\World
Comment
• title() • strip()
• upper() • lstrip()
• lower() • rstrip()
• swapcase() • find()
• isalpha()
• startswith()
• isdigit()
• endswith()
• islower()
• replace()
• isupper()
• istitle()
• split()
Using string functions
>>> s = u'\u0937'
>>> print(s)
ष
>>> s = u'\u0567'
>>> print(s)
Է
s = u'\u0756'
>>> print(s)
ݖ
The dir( ) function
>>> print(name,age)
Tushar 34
>>> print(name,age,sep='\t')
Tushar 34
>>> print(name,age,sep='\n')
Tushar
34
The format( )
name = 'Tushar'
age = 34
• # default arguments
print("Hello { }, your age is { }.".format(name,age))
• # positional arguments
print("Hello {0}, your age is {1}.".format(name,age))
• # keyword arguments
print("Hello {x}, your age is {y}.".format(x=name, y=age))
• # mixed arguments
print("Hello {0}, your age is {y}.".format(name, y=age))
Format specifiers
>>> print(num1)
25
>>> num1 += 2
>>> print(num1)
27
>>> num1 *= 2
>>> print(num1)
54
>>> num1 /= 2
>>> print(num1)
27.0
Logical operators
Logical operators
>>> x = 10
>>> x in [34,10,32,17]
True
>>> 15 in [34,10,32,17]
False
>>> 15 not in [34,10,32,17]
True
>>> 'kar' in 'Tendulkar'
True
Identity operators
>>> 2 is 2
True
>>> 2 is '2'
False
>>> 20 is 20.0
False
>>> 20 is not 20.0
True
>>> 2000.0 is 2e3
True
Bitwise operators
Bitwise operators
>>> x = 19; y = 34
>>> x & y
2
>>> x | y
51
>>> x ^ y
49
>>> y << 2
136
>>> ~x
-20
Operators Precedence
Two more types
• Complex
>>> num = 2.3 + 4.5j
>>> print(num)
(2.3+4.5j)
>>> type(num)
<class 'complex'>
• Boolean
>>> num = True
>>> print(num)
True
>>> type(num)
<class 'bool'>
Special type: None
>>> num1 = 45
>>> num2 = 56.23
>>> result = num1 + int(num2)
>>> print(result)
101
Type casting on strings
Web Resources
http://mitu.co.in
http://tusharkute.com