Python Programming
Python Programming
Understand __main__:-
def main():
print "hello world!"
print "good bye"
Here we got two pieces of print one is defined within a main function that is "Hello
World" and the other is independent which is "python". When you run the function
def main ():
When Python interpreter reads a source file, it will execute all the code found
in it.
When Python runs the "source file" as the main program, it sets the special
variable (__name__) to have a value ("__main__").
When you execute the main function, it will then read the "if" statement and
checks whether __name__ does equal to __main__.
In Python "if__name__== "__main__" allows you to run the Python files
either as reusable modules or standalone programs.
Like C, Python uses == for comparison while = for assignment. Python interpreter
uses the main function in two ways
direct run:__name__=__main__
It is important that after defining the main function, you call the code by
if__name__== "__main__" and then run the code, only then you will get the
output "hello world!" in the programming console as shown below.
def main():
print(“hello world”)
if __name__ =” __main__”:
main()
print(“good bye”)
Note: Make sure that after defining a main function, you leave some indent and not
declare the code right below the def main(): function otherwise it will give indent
error.
def main():
print("Hello World!")
if __name__== "__main__":
main()
print("Python")
Above examples are Python 3 codes, if you want to use Python 2, please consider
following code
def main():
print "Hello World!"
if __name__== "__main__":
main()
print "Python"
Next Topic:-Python Variables: Declare, Concatenate, Global & Local
Every value in Python has a datatype. Different data types in Python are
Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any
name or even alphabets like a, aa, abc, etc.
Let see an example. We will declare variable "a" and print it.
a=100
print a
Re-declare a Variable
You can re-declare the variable even after you have declared it once.
Python 2 Example
Python 3 Example
Let's see whether you can concatenate different data types like string and number
together. For example, we will concatenate “pyhton" with the number "99".
Unlike Java, which concatenates number with string without declaring number as
string, Python requires declaring the number as string otherwise it will show a
TypeError.
a="python"
b = 99
print a+b
Once the integer is declared as string, it can concatenate both "Python" + str("99")=
"python" in the output.
a="python"
b = 99
print(a+str(b))
In Python when you want to use the same variable for rest of your program or
module you declare it a global variable, while if you want to use the variable in a
specific function or method, you use a local variable.
Let's understand this difference between local and global variable with the below
program.
1. Variable "f" is global in scope and is assigned value 101 which is printed in
output
2. Variable f is again declared in function and assumes local scope. It is
assigned value "I am learning Python." which is printed out as an output. This
variable is different from the global variable "f" define earlier
3. Once the function call is over, the local variable f is destroyed. At line 12,
when we again, print the value of "f" is it displays the value of global variable
f=101
Using the keyword global, you can reference the global variable inside a
function.
1. Variable "f" is global in scope and is assigned value 101 which is printed
in output
3. We changed the value of "f" inside the function. Once the function
call is over, the changed value of the variable "f" persists. At line
12, when we again, print the value of "f" is it displays the value
"changing global variable"
Delete a variable
You can also delete variable using the command del "variable name".
In the example below, we deleted variable f, and when we proceed to print it,
we get error "variable name is not defined" which means you have deleted
the variable.
Next Topic:-Python Strings: Replace, Join, Split, Reverse, Uppercase &
Lowercase
We use square brackets for slicing along with the index or indices to obtain a
substring.
var1 = "Python!"
var2 = "Software Testing"
print ("var1[0]:",var1[0])
print ("var2[1:5]:",var2[1:5])
[] Slice- it gives the letter from a[1] will give "u" from the word Python as such ( x="Python"
the given index 0=G, 1=u, 2=r and 3=u) print x[1]
[:] Range slice-it gives the x [1:3] it will give "ur" from the word Python. x="Python"
characters from the given Remember it will not consider 0 which is G, it will print x[1:3]
range consider word after that is ur.
in Membership-returns true if a u is present in word Python and hence it will give x="Python"
letter exist in the given string 1 (True) print "u" in x
not in Membership-returns true if a l not present in word Python and hence it will x="Python"
letter exist is not in the given give 1 print "l" not in x
string
r/R Raw string suppresses actual Print r'\n' prints \n and print R'/n' prints \n
meaning of escape characters.
% - Used %r - It insert the canonical The output of this code will be "python 99". name = 'pyhton'
for string string representation of the number = 99
format object (i.e., repr(o)) %s- It print'%s %d' %
insert the presentation string (name,number)
representation of the object
(i.e., str(o)) %d- it will format a
number for display
x = "Hello World!"
print(x[:6])
print(x[0:6] + "Python99")
The method replace() returns a copy of the string in which the values of old
string have been replaced with the new value.
In Python, you can even change the string to upper case or lower case.
string="python at python99"
print(string.upper())
Likewise, you can also do for other function as well like capitalize
string="python at python99"
print(string.capitalize())
string="PYTHON AT PYTHON99"
print(string.lower())
For example, if you want to add a colon (:) after every character in the string
"Python" you can use the following code.
print(":".join("Python"))
Reversing String
By using the reverse function, you can reverse the string. For example, if we
have string "12345" and then if you apply the code for the reverse function as
shown below.
string="12345"
print(''.join(reversed(string)))
Split Strings
Split strings is another function that can be applied in Python let see for string
"python99 career python99". First here we will split the string by using the
command word.split and get the result.
To understand this better we will see one more example of split, instead of
space (' ') we will replace it with ('r') and it will split the string wherever 'r' is
mentioned in the string
Important Note:
x = "Python99"
x.replace("Python99","Python")
print(x)
x = "Python99"
x = x.replace("Python99","Python")
print(x)
Tuple Syntax
Tup = ('Jan','feb','march')
tup1 = ();
For writing tuple for a single value, you need to include a comma, even though
there is a single value. Also at the end you need to write semicolon as shown
below.
Tup1 = (50,);
Tuple indices begin at 0, and they can be concatenated, sliced and so on.
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than
one variable at a time. In here, we have assigned tuple 1 with the persons
information like name, surname, birth year, etc. and another tuple 2 with the
values in it like number (1,2,3,….,7).
For Example,
(name, surname, birth year, favorite movie and year, profession, birthplace) =
Robert
Comparing tuples
A comparison operator in Python can work with tuples.
The comparison starts with a first element of each tuple. If they do not
compare to =,< or > then it proceed to the second element and so on.
It starts with comparing the first element from each of the tuples
#case 1
a=(5,6)
b=(1,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
#case 2
a=(5,6)
b=(5,4)
if (a>b):print("a is bigger")
else: print ("b is bigger")
#case 3
a=(5,6)
b=(6,4)
if (a>b):print("a is bigger")
else: print("b is bigger")
Case1: Comparison starts with a first element of each tuple. In this case 5>1,
so the output a is bigger
Case 2: Comparison starts with a first element of each tuple. In this case 5>5
which is inconclusive. So it proceeds to the next element. 6>4, so the output a
is bigger
Case 3: Comparison starts with a first element of each tuple. In this case 5>6
which is false. So it goes into the else loop prints "b is bigger."
directory[last,first] = number
Inside the brackets, the expression is a tuple. We could use tuple assignment
in a for loop to navigate this dictionary.
Dictionary can return the list of tuples by calling items, where each tuple is a
key value pair.
a = {'x':100, 'y':200}
b = list(a.items())
print(b)
Deleting Tuples
Tuples are immutable and cannot be deleted, but deleting tuple entirely is
possible by using the keyword "del."
Slicing of Tuple
To fetch specific sets of sub-elements from tuple or list, we use this unique
function called slicing. Slicing is not only applicable to tuple but also for array
and list.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
You can access the items of a dictionary by referring to its key name,
inside square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use
the len() method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use
the len() method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example
The popitem() method removes the last inserted item (in versions
before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example
The clear() keyword empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Example
Make a copy of a dictionary with the dict() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)