Beruflich Dokumente
Kultur Dokumente
Variables:
variablea are reserved memory space to store values.
based on the data type of the variable, the interpreter allocate memory and deci
des what can be stored in the reserved memory.
python variables do not have to be explicitly declared 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.
eg:
counter = 100
miles = 1000.02
name = "Ranjit"
print counter
print miles
print name
Data Types:
Python has 5 data types:
Numbers
string
list
tuple
dictionary
Numbers: store numeric value, they are immutable data typeswhich means that chan
ging the
value of a number data type results in a newly allocated object
number objects are created when you assign a value to them
eg:
var1 = 1
var2 = 10
to delete a number object use del stmt
del var1[,var2[,var3[....,varN]]]
also
del var
del var_a, var_b
python supports 4 different types of numerical values
1.
2.
3.
4.
int(signed integers)
long(long integers)
float(floating point real values)
complex(complex numbers)
Python strings:
strings = set of contiguous characters btw quotation marks.
eg:
str = 'Hello World!'
print str = prints 'Hello World!'
print str[0] = prints first character of the string = H
print str[2:5] = prints chars starting from 3rd to 5th = llo
print str[2:] = prints chars starting from 3rd char = llo World!
print str * 2 = prints string two times = Hello World!Hello World!
print str + "TEST" = prints concatenated string Hello World!TEST
python lists:
list contains items seperated by commas and enclosed within []
items in lists can be of different data types
eg:
list = ['abcd', 786, 2.43, 'Kumar', 10.2]
Python tuples:
Is same like a list but the tuples are enclosed in paranthesis ()
Lists size can be changed while tuples can not be updated.
eg:
tuple = ('abcd', 786, 10.2, 'Kumar')
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
python dictionaries:
A dictionary key can be almost any python type, but are usually
numbers or strings values.
Dictionaries are enclosed in {}, values can be assigned and accessed using []
eg:
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values