Python Programming Help | Python Tutorial



In this blog we will cover all of the python topics which is important for everyone. If you have not any previous knowledge about python then learn python tutorial from: If you have no knowledge of programming, then the official Python tutorial is a good place to start.


Boolean Operations

Frequently, one wants to combine or modify boolean values. Python has several operations for just this purpose:

  • not a: returns the opposite value of a.

  • a and b: returns true if and only if both a and b are true.

  • a or b: returns true either a or b are true, or both.

Like mathematical expressions, boolean expressions can be nested using parentheses.


var1 = 5
var2 = 6
var3 = 7 

print(var1 + var2 == 11 and var2 + var3 == 13)
print(var1 + var2 == 12 and var2 + var3 == 13)
print(var1 + var2 == 12 or var2 + var3 == 13)

Output

True False True



String Formatting:


Often one wants to embed other information into strings, sometimes with special formatting constraints. In python, one may insert special formatting characters into strings that convey what type of data should be inserted and where, and how the "stringified" form should be formatted. For instance, one may wish to insert an integer into a string:


message = 2
print("To be or not %.2f be" % message)

Output

To be or not 2.00 be


Note the %d formatting (or conversion) specifier in the string. This is stating that you wish to insert an integer value (more on these conversion specifiers below). Then the value you wish to insert into the string is separated by a % character placed after the string. If you wish to insert more than one value into the string being formatted, they can be placed in a comma separated list, surrounded by parentheses after the %


print("%d be or not %d be" % (2, 2))

Output

2 be or not 2 be


In detail, a conversion specifier contains two or more characters which must occur in order with the following components:

  • The % character which marks the start of the specifier

  • An optional minimum field width. The value being read is padded to be at least this width

  • An optional precision value, given as a "." followed by the number of digits precision.

  • Conversion specifier flag specified below.

For a more detailed treatment on string formatting options, see here.

Some common conversion flag characters are:

  • d: Signed integer decimal.

  • i: Signed integer decimal.

  • e: Floating point exponential format (lowercase).

  • E: Floating point exponential format (uppercase).

  • f: Floating point decimal format.

  • 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()).


print("%d %s or not %02.3f %c" % (2, "be", 10.0/3, 'b'))

Output

2 be or not 3.333 b


Exercise

  • Divide 10 by 3 and print the percentage with two decimal points

print("%s is %02.2f" % ("The Result upto 2 decimal places", 10.0/3))

Output

The Result upto 2 decimal places is 3.33



Python Data Structures


We have covered in detail much of the basics of python's primitive data types. Its now useful to consider how these basic types can be collected in ways that are meaningful and useful for a variety of tasks. Data structures are a fundamental component of programming, a collection of elements of data that adhere to certain properties, depending on the type. In these notes, we'll present three basic data structures, the list, the set, and the dictionary. Python data structures are very rich, and beyond the scope of this simple primer. Please see the documentation for a more complete view.


List:

A list, sometimes called an array or a vector is an ordered collection of values. The value of a particular element in a list is retrieved by querying for a specific index into an array. Lists allow duplicate values, but indicies are unique. In python, like most programming languages, list indices start at 0, that is, to get the first element in a list, request the element at index 0. Lists provide very fast access to elements at specific positions, but are inefficient at "membership queries," determining if an element is in the array.

In python, lists are specified by square brackets, [ ], containing zero or more values, separated by commas. Lists are the most common data structure, and are often generated as a result of other functions, for instance, a_string.split(" ").

To query a specific value from a list, pass in the requested index into square brackets following the name of the list. Negative indices can be used to traverse the list from the right.


a_list = [1, 2, 3, 0, 5, 10, 11]
a_list[0:2]

Output

[1, 2]


print(a_list[-1]) # indexing from the right
print(a_list[2:])

Output

11 [3, 0, 5, 10, 11]



another_list = ["a", "b", "c"]
empty_list = []
mixed_list = [1, "a"]

print(another_list[1])

print(empty_list)

Output

b []



Some common functionality of lists:

  • list.append(x): add an element ot the end of a list

  • list_1.extend(list_2): add all elements in the second list to the end of the first list

  • list.insert(index, x): insert element x into the list at the specified index. Elements to the right of this index are shifted over

  • list.pop(index): remove the element at the specified position

  • list.index(x): looks through the list to find the specified element, returning it's position if it's found, else throws an error

  • list.count(x): counts the number of occurrences of the input element

  • list.sort(): sorts the list of items, list.sort(key = , reverse = True/False) default is False.

  • list.reverse(): reverses the order of the list


a = ["Python", "is", "one"]
a.sort(key=len, reverse = True)
a

Output

['Python', 'one', 'is']



Exercise

  • Add the letter "d" in another_list and print the result

  • Add the letter "c" in another_list and print the result

  • If you search for "c" in another_list using the list.index(x) command, what is the result?

  • Sort another_list and print the result


#Add the letter "d" in another_list and print the result
another_list.append("d")
print(another_list)

Output

['a', 'b', 'c', 'd']



#Add the letter "c" in another_list and print the result
another_list.append("c")
print(another_list)

Output

['a', 'b', 'c', 'd', 'c']



#If you search for "c" in another_list using the list.index(x) command, what is the result?
another_list.index("c")


Output

2



#Sort another_list and print the result
another_list.sort()

print(another_list)

Output

['a', 'b', 'c', 'c', 'd']



Set

A set is a data structure where all elements are unique. Sets are unordered. In fact, the order of the elements observed when printing a set might change at different points during a programs execution, depending on the state of python's internal representation of the set. Sets are ideal for membership queries, for instance, is a user amongst those users who have received a promotion?

Sets are specified by curly braces, { }, containing one or more comma separated values. To specify an empty set, you can use the alternative construct, set().


some_set = {1, 2, 3, 4}
another_set = {4, 5, 6}
empty_set = set()

print(some_set)
print(another_set)
print(empty_set)

len(some_set)

Output

{1, 2, 3, 4}

{4, 5, 6}

set()

4


We can also create a set from a list:

my_list = [1, 2, 3, 0, 5, 10, 11, 1, 5]
your_list = [1, 2, 3, 0, 11, 10]
my_set = set(my_list)
your_set = set(your_list)
print(my_set)
print(your_set)

Output

{0, 1, 2, 3, 5, 10, 11}

{0, 1, 2, 3, 10, 11}


type(my_set)

Output:

set


print(my_set.issubset(your_set))
print(type(my_set))
print(len(my_set))

Output:

False <class 'set'> 7


The easiest way to check for membership in a set is to use the `in` keyword, checking if a needle is "`in`" the haystack set.


my_set = {1, 2, 3}
print("The value 1 appears in the variable some_set:", 1 in my_set)
print("The value 0 appears in the variable some_set:", 0 in my_set)
print(1 in my_set)
print(4 not in my_set)

Output:

The value 1 appears in the variable some_set: True The value 0 appears in the variable some_set: False True True



We also have the "not in" operator

some_set = {1, 2, 3, 4}
val = 5
print("Check that the value %d does not appear in the variable some_set:" % val, (val not in some_set))
val = 1
print("Check that the value %d does not appear in the variable some_set:" % val, (val not in some_set))

Output:

Check that the value 5 does not appear in the variable some_set: True Check that the value 1 does not appear in the variable some_set: False



Some other common set functionality:

  • set_a.add(x): add an element to a set

  • set_a.remove(x): remove an element from a set

  • set_a - set_b: elements in a but not in b. Equivalent to set_a.difference(set_b)

  • set_a | set_b: elements in a or b. Equivalent to set_a.union(set_b)

  • set_a & set_b: elements in both a and b. Equivalent to set_a.intersection(set_b)

  • set_a ^ set_b: elements in a or b but not both. Equivalent to set_a.symmetric_difference(set_b)

  • set_a <= set_b: tests whether every element in set_a is in set_b. Equivalent to set_a.issubset(set_b)


some_set = {1, 2, 3, 4}
another_set = {4, 5, 6}


Exercise

Try the above yourself using the some_set and another_set variables from above

  • find the set of elements in some_set but not in another_set

  • find the set of elements in either some_set or in another_set

  • find the set of elements in both some_set and another_set

  • remove the element 4 from some_set

  • add an element 7 to "another_set


#find the set of elements in some_set but not in another_set
some_set.difference(another_set)


Output:

{1, 2, 3}


#find the set of elements in either some_set or in another_set
some_set.union(another_set)

Output:

{1, 2, 3, 4, 5, 6}



#find the set of elements in both some_set and another_set
some_set.intersection(another_set)

Output

{4}


#remove the element 4 from some_set
some_set.remove(4)
some_set

Output

{1, 2, 3}


#add an element 7 to "another_set
another_set.add(7)
another_set

Output

{4, 5, 6, 7}



Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.


t = 12345, 54321, 'hello!'
print(t)
type(t)

Output:

(12345, 54321, 'hello!') tuple


print(t[2])

Output

hello!


len(t)

Output:

3


# Empty tuple
t_2=()
print(t_2)
type(t_2)

Output:

() tuple


t_3 = (1,)
type(t_3)
len(t_3)

Output:

1


#Concatenation
print((1, 2, 3) + (4, 5, 6))