Variables

Python is strongly typed, which means that the type of an object does not change, even if its value is mutable.

Variables are just names. Assignment does not copy a value; it just attaches a name to the object that contains the data. The name is a reference to a thing rather than the thing itself. Think of a name as a sticky note.

e.g

variable = 3
variable = 'hello'
print(variable)
hello

 

So hasn’t variable just changed type ? The answer is a resounding novariable isn’t an object at all – it’s a name. In the first statement we create an integer object with the value 3 and bind the name ‘variable’ to it. In the second statement we create a new string object with the value hello, and rebind the name ‘variable’ to it.

Variable names can only contain these characters:

• Lowercase letters (a through z)
• Uppercase letters (A through Z)
• Digits (0 through 9)
• Underscore (_)

Names cannot begin with a digit. Also, Python treats names that begin with an underscore in special ways.

 

Underscore:
  • _single_leading_underscore:
    weak
    “internal use” indicator. E.g. “from M import *” does not import objects whose name starts with an underscore.
  • single_trailing_underscore_:
    used by convention to avoid conflicts
    with Python keyword, e.g. Tkinter.Toplevel(master, class_=‘ClassName’)
  • __double_leading_underscore:
    when naming a
    class attribute, invokes name mangling. This comply with the naming convention for attributes that should not be visible outside of their class definition.  (inside class FooBar, __boo becomes _FooBar__boo).

>> class Duck():
def __init__(self,input_name):
self.__name=input_name
@property
def name(self):
print(‘inside the getter’)
return self.__name
@name.setter
def name(self,input_name):
print(‘inside the setter’)
self.__name=input_name

>>> fowl=Duck(‘frank’)
>>> fowl.name
inside the getter
‘frank’

If you try to access the attribute directly, an error message will pop up.

>> fowl.__name
Traceback (most recent call last):
File “<pyshell#118>”, line 1, in <module>
fowl.__name
AttributeError: ‘Duck’ object has no attribute ‘__name’

Although it is discouraged to do, any way, there is a way to access the attribute(add the class name before the __):

>> fowl._Duck__name
‘frank’

  • __double_leading_and_trailing_underscore__:
    “magic” objects or attributes that live in usercontrolled namespaces. E.g. __init__, __import__ or __file__. Never invent such names; only use them as documented.

Python’s triple quotes(”’) are handy when creating long strings such as SQL queries.

If you want to know the type of anything (a variable or a literal value), use type( thing ).

Finally, don’t use any of these for variable names, because they are Python’s reserved words:

False class finally is return 
None continue for lambda try 
True def from nonlocal while 
and del global not with as 
elif if or yield assert else 
import pass break except in raise 
Placeholder:

The old way is use a % followed by a single letter conversion, e.g

Old

'%s %s' % ('one', 'two')

output

one two

%s is used as a placeholder for string values you want inject into a formatted string. You can replace the ‘one’ , ‘two’ with a string variable.

Old

'%d %d' % (1, 2)

output

1 2

%d is used as a placeholder for numeric or decimal values.

Conversion Meaning
'd' Signed integer decimal.
'i' Signed integer decimal.
'o' Signed octal value.
'u' Obsolete type – it is identical to 'd'.
'x' Signed hexadecimal (lowercase).
'X' Signed hexadecimal (uppercase).
'e' Floating point exponential format (lowercase).
'E' Floating point exponential format (uppercase).
'f' Floating point decimal format.
'F' Floating point decimal format.
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or

not less than precision, decimal format otherwise.

'G' Floating point format. Uses uppercase exponential format if exponent is less than -4 or

not less than precision, decimal format otherwise.

'c' Single character (accepts integer or single character string).
'r' String (converts any Python object using repr()).
's' String (converts any Python object using str()).
'%' No argument is converted, results in a '%' character in the result.

Any way, there is new way to use {} as place holder

New

'{} {}'.format('one', 'two')

Output

one two

Accessing arguments by position:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'

A class is the definition of an object.

Accessing arguments by name:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'

 

Numbers

The operators:

Operator Description Example Result
+ addition 5 + 8 13
subtraction 90-10 80
* multiplication 4 * 7 28
/ floating point division 7/2 3.5
// integer ( truncation) division,discard the reminder 7//2 3
% modulus (remainder) 7%3 1
** exponentiation  3 ** 4 81

 

 

a = a + 8:
>>> a += 8
>>> a
100

And this is like a = a * 2:

>> a *= 2
>>> a
200

Here’s a floating-point division example, such as a = a / 3:

>>> a /= 3
>>> a

 

Here’s how to get both the (truncated) quotient and remainder at once by function divmod:

>>>divmod(9,5)
(1, 4)

Bases

Integers are assumed to be decimal (base 10) unless you use a prefix to specify another base.

In Python, you can express literal integers in three bases besides decimal:

• 0b or 0B for binary (base 2). note that it’s zero b.
• 0o or 0O for octal (base 8).
• 0x or 0X for hex (base 16).

The interpreter prints these for you as decimal integers. Let’s try each of these bases.

First, a plain old decimal 10, which means 1 ten and 0 ones:

>> 10
10

Now, a binary (base two), which means 1 (decimal) two and 0 ones:

>> 0b10
2

Octal (base 8) for 1 (decimal) eight and 0 ones:

>> 0o10
8

Hexadecimal (base 16) for 1 (decimal) 16 and 0 ones:

>>> 0x10
16

Converting a floating-point number to an integer just lops off everything after the decimal point:

>>> int(98.6)
98
>>> int(1.0e4)
10000

Finally, here’s an example of converting a text string (you’ll see more about strings in a few pages) that contains only digits, possibly with + or – signs:

>>> int(’99’)
99
>>> int(‘-23’)
-23
>>> int(‘+12’)
12

If you try to convert something that doesn’t look like a number, you’ll get an exception:

>>> int(’99 bottles of beer on the wall’)
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
ValueError: invalid literal for int() with base 10: ’99 bottles of beer on the wall’

In Python 2, the size of an int was limited to 32 bits. This was enough room to store any integer from –2,147,483,648 to 2,147,483,647.
A long had even more room: 64 bits, allowing values from –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. In Python 3, long is long gone, and an int can be any size —even greater than 64 bits.

Floats

Integers are whole numbers, but floating-point numbers (called floats in Python) have decimal points. Floats are handled similarly to integers: you can use the operators (+, –, *, /, //, **, and %) and divmod() function.

To convert other types to floats, you use the float() function. As before, booleans act like tiny integers:

>> float(True)
1.0
>>> float(False)
0.0

Converting an integer to a float just makes it the proud possessor of a decimal point:

>> float(98)
98.0
>>> float(’99’)
99.0

And, you can convert a string containing characters that would be a valid float (digits,
signs, decimal point, or an e followed by an exponent) to a real float:

> float(‘98.6’)
98.6
>>> float(‘-1.5’)
-1.5
>>> float(‘1.0e4’)
10000.0

Fomating floats:

Limiting decimal points: use place holder %.nf to show n digit after the decimal point:

 >>> a=13.946
 >>> print(a)
  13.946
 >>> print("%.2f" % a)
  13.95

 

Strings

Strings are defined either with a single quote or a double quotes.

mystring = 'hello'
mystring = "hello"

Formatting strings

%s acts a placeholder for a string while %d acts as a placeholder for a number.

mystring = “hello”
myfloat = 10.0
myint = 20

# testing code
if mystring == “hello”:
print “String: %s” % mystring
if isinstance(myfloat, float) and myfloat == 10.0:
print “Float: %d” % myfloat
if isinstance(myint, int) and myint == 20:
print “Integer: %d” % myint

Convert Data Types by Using str()

You can convert other Python data types to strings by using the str() function:

>> str(98.6)
‘98.6’
>>> str(1.0e4)
‘10000.0’
>>> str(True)
‘True

 

If you have multiple lines within triple quotes, the line ending characters will be preserved in the string. If you have leading or trailing spaces, they’ll also be kept:

>> poem2 = ”’I do not like thee, Doctor Fell.
… The reason why, I cannot tell.
… But this I know, and know full well:
… I do not like thee, Doctor Fell.
… ”’
>>> print(poem2)
I do not like thee, Doctor Fell.
The reason why, I cannot tell.
But this I know, and know full well:
I do not like thee, Doctor Fell.
>>>

Finally, there is the empty string, which has no characters at all but is perfectly valid. You can create an empty string with any of the aforementioned quotes:

>>> ”

>>> “”

>>> ”””

>>> “”””””

Escape with \

Python lets you escape the meaning of some characters within strings to achieve effects that would otherwise be hard to express. By preceding a character with a backslash (\), you give it a special meaning.

  • The most common escape sequence is \n, which means to begin a new line. With this you can create multiline strings from a one-line string.

>> palindrome = ‘A man,\nA plan,\nA canal:\nPanama.’
>>> print(palindrome)
A man,
A plan,
A canal:
Panama.

  • \t (tab) used to align text:

>> print(‘\tabc’)
abc
>>> print(‘a\tbc’)
a bc
>>> print(‘ab\tc’)
ab c
>>> print(‘abc\t‘)
abc

  • \’ or \” to specify a literal single or double quote inside a string that’s quoted by the same character:

>> testimony = “\I did nothing!\he said. \Not that either! Or the other thing.\
>>> print(testimony)
“I did nothing!” he said. “Not that either! Or the other thing.”

 

Combine with +

You can combine literal strings or string variables in Python by using the + operator, as demonstrated here:

>> ‘Release the kraken! ‘ + ‘At once!’
‘Release the kraken! At once!’

Duplicate with *

You use the * operator to duplicate a string. Try typing these lines into your interactive interpreter and see what they print:

>>> start = ‘Na ‘ * 4 + ‘\n
>>> middle = ‘Hey ‘ * 3 + ‘\n
>>> end = ‘Goodbye.’
>>> print(start + start + middle + end

Extract a Character with []

To get a single character from a string, specify its offset inside square brackets after the string’s name. The first (leftmost) offset is 0, the next is 1, and so on.

The last (rightmost) offset can be specified with –1 so you don’t have to count; going to the left are –2, –3, and so on.

If you specify an offset that is the length of the string or longer (remember, offsets go from 0 to length–1), you’ll get an exception:

>> letters[100] Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
IndexError: string index out of range

replace() or a slice

Replace() will replace all the letters.

 

> name = ‘Henny’
>>> name.replace(‘H’, ‘P’)
‘Penny’
>>> ‘P’ + name[1:] ‘Penny’

Remove string with strip()

 

>> setup = ‘a duck goes into a bar…’
>>> setup.strip(‘.’)
‘a duck goes into a bar’

strip() is just a Python str method to remove leading and trailing whitespace.

Slice with [ start : end : step ]

You can extract a substring (a part of a string) from a string by using a slice. You define a slice by using square brackets, a start offset, an end offset, and an optional step size.
Some of these can be omitted.

The slice will include characters from offset start to one before end.

• [:] extracts the entire sequence from start to end.
• [ start :] specifies from the start offset to the end.
• [: end ] specifies from the beginning to the end offset minus 1.
• [ start : end ] indicates from the start offset to the end offset minus 1.
• [ start : end : step ] extracts from the start offset to the end offset minus 1,skipping characters by step.

As before, offsets go 0, 1, and so on from the start to the right, and –1,–2, and so forth from the end to the left. If you don’t specify start, the slice uses 0 (the beginning). If you don’t specify end, it uses the end of the string.
Let’s make a string of the lowercase English letters:

>> letters = ‘abcdefghijklmnopqrstuvwxyz’

Using a plain : is the same as 0: (the entire string):

>> letters[:] ‘abcdefghijklmnopqrstuvwxyz’

Here’s an example from offset 20 to the end:

>> letters[20:] ‘uvwxyz’

In this next example, we go from offset 18 to the fourth before the end; notice the difference from the previous example, in which starting at –3 gets the x, but ending at–3 actually stops at –4, the w:

>> letters[18:-3] ‘stuvw’

In the following, we extract from 6 before the end to 3 before the end:

>> letters[-6:-2] ‘uvwx

From the start to the end, in steps of 7 characters:

>> letters[::7] ‘ahov

Given a negative step size, this handy Python slicer can also step backward. This starts at the end and ends at the start, skipping nothing:

>> letters[-1::-1] ‘zyxwvutsrqponmlkjihgfedcba’

It turns out that you can get the same result by using this:

>> letters[::-1] ‘zyxwvutsrqponmlkjihgfedcba’

split with split()

You can use the built-in string split() function to break a string into a list of smaller strings based on some separator.

>>> todos = ‘get gloves,get mask,give cat vitamins,call ambulance’
>>> todos.split(‘,’)
[‘get gloves’, ‘get mask’, ‘give cat vitamins’, ‘call ambulance’]

You specify the string that glues everything together first, and then the list of strings to glue: string .join( list ). So, to join the list lines with separating newlines, you would say ‘\n’.join(lines). In the following example, let’s join some names in a list
with a comma and a space:

> crypto_list = [‘Yeti’, ‘Bigfoot’, ‘Loch Ness Monster’] >>> crypto_string = ‘, ‘.join(crypto_list)
>>> print(‘Found and signing book deals:’, crypto_string)
Found and signing book deals: Yeti, Bigfoot, Loch Ness Monster

Captalize

Capitalize the first word:

> setup.capitalize()

‘A duck goes into a bar…’

Capitalize all the words:

>> setup.title()
‘A Duck Goes Into A Bar…’

Convert all characters to uppercase:

>> setup.upper()
‘A DUCK GOES INTO A BAR…’

Convert all characters to lowercase:

>> setup.lower()
‘a duck goes into a bar…’

Swap upper- and lowercase:

>> setup.swapcase()
‘a DUCK GOES INTO A BAR…’

Allignment

The string is aligned within the specified total number of spaces (30 here).

Center the string within 30 spaces:

>> setup.center(30)
‘ a duck goes into a bar… ‘

Left justify:

>> setup.ljust(30)
‘a duck goes into a bar… ‘

Right justify:

>> setup.rjust(30)
‘ a duck goes into a bar…’

Substitute with replace()

You give it the old substring, the new one, and how many instances of the old substring to replace. If you omit this final count argument, it replaces all instances. In this example, only one string is matched
and replaced:

>> setup.replace(‘duck’, ‘marmoset’)
‘a marmoset goes into a bar…’

To change up to 100 of them:

>> setup.replace(‘a ‘, ‘a famous ‘, 100)
‘a famous duck goes into a famous bar…’

 

Other

Does it start with the letters All?

>> poem.startswith(‘All’)
True

Does it end with That’s all, folks!?

>> poem.endswith(‘That\’s all, folks!’)
False

Now, let’s find the offset of the first occurrence of the word the in the poem:

>>> word = ‘the’
>>> poem.find(word)
73

And the offset of the last the:

>> poem.rfind(word)
214

How many times does the three-letter sequence the occur?

>> poem.count(word)
3

Are all of the characters in the poem either letters or numbers?

>> poem.isalnum()
False