In computer programming, a variable is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value.
int x = 29;
float y = 321.321;
double z = 32132132132133.21;
x = 343 # Integer
y = 4324n4324 # Flaot
Variable names in Python can contain alphanumerical characters a-z, A-Z, 0-9 and some special characters such as _
. Normal variable names should start with a letter. _
can be used for special cases.
By convension, variable names start with a lower-case letter, and Class names start with an upper-case letter.
In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:
and, as, assert, break, class, continue, def, del, elif, else, except,
exec, finally, for, from, global, if, import, in, is, lambda, not, or,
pass, print, raise, return, try, while, with, yield
Note: Be aware of the keyword lambda
, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.
In [1]:
'''
variable assignments
this is a variable assignment
'''
x = 1.0
my_variable = 12
In [2]:
print type(x)
print type(my_variable)
If we assign a new value to a variable, its type can change.
In [3]:
x = 1
type(x)
Out[3]:
We get a NameError
when we try to access a variable which has not been defined.
In [4]:
t = x + y
In [5]:
# integers
x = 1
type(x)
Out[5]:
In [6]:
# float
x = 1.0
type(x)
Out[6]:
In [7]:
# boolean
b1 = True
b2 = False
type(b1)
Out[7]:
In [8]:
# Booleans are integers in Python
print True + True # True has a value equal to 1
print False + False # False has a value equal to 0
In [9]:
# complex numbers: note the use of `j` to specify the imaginary part
x = 1.0 - 1.0j
type(x)
Out[9]:
In [10]:
print x
In [11]:
# Real part
print x.real
In [12]:
# Imaginary
print x.imag
In [13]:
a = 1
a
Out[13]:
In [14]:
float(a)
Out[14]:
In [15]:
z = 2 + 3j
z
Out[15]:
In [16]:
float(z.imag)
Out[16]:
In [17]:
complex(a)
Out[17]:
In [18]:
int(45.55)
Out[18]:
In [19]:
bool(0)
Out[19]:
In [20]:
True and True
Out[20]:
In [21]:
True and False
Out[21]:
In [22]:
True and True and False and True
Out[22]:
In [23]:
True or False
Out[23]:
In [24]:
False or False
Out[24]:
In [25]:
1 and 1
Out[25]:
In [26]:
1 and 0
Out[26]:
In [27]:
20 and 30 # It just gives you the latter
Out[27]:
In [28]:
200 and 30 # I told ya!
Out[28]:
In [29]:
0 and 431 # Not here!
Out[29]:
In [30]:
1 or 1
Out[30]:
In [31]:
1 or 0
Out[31]:
In [32]:
21 or 42 # Gives you former
Out[32]:
In [33]:
3214 or 42 # Proved!
Out[33]:
In [34]:
not True
Out[34]:
In [35]:
not False
Out[35]:
In [36]:
not 1
Out[36]:
In [37]:
not 0
Out[37]:
In [38]:
not 420 # Yep!
Out[38]:
In [39]:
1 < 2
Out[39]:
In [40]:
2 != 3
Out[40]:
In [41]:
22 > 11
Out[41]:
In [42]:
5 == 5
Out[42]:
In [43]:
2 + 3 == 5
Out[43]:
In [44]:
s = "Hello world"
type(s)
Out[44]:
In [45]:
# length of the string: the number of characters
len(s)
Out[45]:
In [46]:
s # `s` is still the same! Strings are immutable.
Out[46]:
In [47]:
s[0]
Out[47]:
In [48]:
s[1]
Out[48]:
In [49]:
s[2], s[3], s[4]
Out[49]:
In [50]:
s[0:5]
Out[50]:
In [51]:
s[:5] # From start.
Out[51]:
In [52]:
s[6:] # Till end.
Out[52]:
In [53]:
s[:] # From start and till end!
Out[53]:
In [54]:
a = "foo"
b = "bar"
a + b
Out[54]:
In [55]:
a + " " + b
Out[55]:
In [56]:
s.count("l")
Out[56]:
In [57]:
s.endswith("ld") # Also works with range
Out[57]:
In [58]:
s.upper()
Out[58]:
In [59]:
s.lower()
Out[59]:
In [60]:
s2 = " " + s + "\n"
s2
Out[60]:
In [61]:
s2.strip() # Performs both lstrip() and rstrip()
Out[61]:
In [62]:
s2.strip("\n")
Out[62]:
In [63]:
s2.split()
Out[63]:
In [64]:
s2.split("l")
Out[64]:
In [65]:
# replace a substring in a string with somethign else
s2.replace("world", "test")
Out[65]:
In [66]:
s2.find("wo")
Out[66]:
In [67]:
s2.index("wo")
Out[67]:
In [68]:
s2.find("te")
Out[68]:
In [69]:
s2.index("te")
In [70]:
list1 = [1, 2, 4, 2]
print list1
list2 = ["hey", "how", "are", "you"]
print list2
In [71]:
list3 = [1, 2, 4, 'hello', '34', 'hi', 23, [45, 23, 7], 2]
print list3
So the best thing about a list is that it can hold any data type inside it and is also very fast. You can iterate through millions of values in a list in a matter of seconds
In [72]:
list1[2]
Out[72]:
In [73]:
list1[-1]
Out[73]:
In [74]:
list4.index(5)
In [75]:
list4.index(6)
In [76]:
list1.append(100)
print list1
In [77]:
list4 = list1 + list2
print list4
In [78]:
list4.pop()
Out[78]:
In [79]:
list4.pop(1)
Out[79]:
In [80]:
print list4
In [81]:
tuple1 = (1, 2, 3)
print list4 + tuple1
In [82]:
list4 = [1,24,5,5]
list4.extend(tuple1)
print list4
In [83]:
list4.count(5)
Out[83]:
In [84]:
list4.sort()
print list4
In [85]:
list5 = ["hey", "how", "are", "you"]
list5.sort()
print list5
In [86]:
list5.sort(key=lambda x : x[len(x)-1]) # Can also take functions as arguments for sorting.
print list5
In [87]:
list5.sort(reverse=True) # Sort in reverse order
print list5
In [88]:
print list5
list5.insert(0, "hi")
print list5
In [89]:
print list5
list5.reverse()
print list5
In [90]:
range(1,20)
Out[90]:
In [91]:
range(1,20,3)
Out[91]:
In [92]:
dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
In [93]:
dict1['Beth'] # Accessing the value of a key
Out[93]:
In [94]:
dict1['Alice'] = '3111' # Editing the value of a key
print dict1
In [95]:
dict1['James'] = '4212' # Adding a value to a dict
print dict1
In [96]:
del dict1['Alice']
print dict1
In [97]:
print dict1.keys()
In [98]:
print dict1.values()
In [99]:
print dict1.items()
In [100]:
print dict1.has_key('Cecil')
In [101]:
dict1['Alice']
In [102]:
print dict1.has_key('Alice')
In [103]:
dict2 = {'a':1, 'b':'54', 'c':'hello'}
In [104]:
dict2.update(dict1)
print dict2
In [105]:
if 2 > 1:
print "Hello World!"
In [106]:
if 1 > 2:
print "Hello World!"
else:
print "World is not a beautiful place!"
In [107]:
if 1 > 2:
print "Hello World!"
elif 2 > 3:
print "World is even better!"
elif 3 > 4:
print "I don't want to live here!"
else:
print "World is not a beautiful place!"
In [108]:
print list1
print s
In [109]:
if 4 in list1:
print "Hey! 2 exists in list1"
In [110]:
if 2 in list1:
i = list1.index(2)
print "Search successful. Found at index {0}".format((i+1))
In [111]:
if 'o' in s:
print "'o' exists!"
In [112]:
if 'llo' in s:
print "'llo' exists!"
In [113]:
if 'house' not in s:
print "house not found!"
In [113]:
In [113]:
In [ ]: