0% found this document useful (0 votes)
113 views

Python Programming

The document discusses Python programming concepts like the __main__ function, variables, strings, and string methods. It explains that the __main__ function allows code to run when a file is executed directly but not when imported. It also covers declaring variables, the difference between local and global variables, built-in string methods like replace(), join(), split(), and converting case.

Uploaded by

Pralay mondal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Python Programming

The document discusses Python programming concepts like the __main__ function, variables, strings, and string methods. It explains that the __main__ function allows code to run when a file is executed directly but not when imported. It also covers declaring variables, the difference between local and global variables, built-in string methods like replace(), join(), split(), and converting case.

Uploaded by

Pralay mondal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

PYTHON PROGRAMMING

Understand __main__:-

Before we jump more into Python coding, we get familiarize with


Python Main function and its importance.

Consider the following code

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 ():

 Only "good bye" prints out


 and not the code "Hello World."

It is because we did not declare the call function "if__name__== "__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

 import: __name__= module's filename

if statement==false, and the script in __main__ will not be executed

 direct run:__name__=__main__

if statement == True, and the script in _main_will be executed


 So when the code is executed, it will check for module name with "if."

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

What is a Variable in Python?

A Python variable is a reserved memory location to store values. In other


words, a variable in a python program gives data to the computer for processing.

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.

How to Declare and use a Variable

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.

Here we have variable initialized to f=0.

Python 2 Example

# Declare a variable and initialize it


f = 0
print f
# re-declaring the variable works
f = 'python'
print f

Python 3 Example

# Declare a variable and initialize it


f = 0
print(f)
# re-declaring the variable works
f = 'python'
print(f)
Concatenate Variables

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.

For the following code, you will get undefined output -

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))

Local & Global Variables

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

2. Variable f is declared using the keyword global. This is NOT a local


variable, but the same global variable declared earlier. Hence when we
print its value, the output is 101

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

Accessing Values in Strings


Python does not support a character type, these are treated as strings of
length one, also considered as substring.

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])

Various String Operators


There are various string operators that can be used in different ways like
concatenating different string.
Suppose if a=python and b=99 then a+b= "python". Similarly, if you are using
a*2, it will "PythonPython". Likewise, you can use other operators in string.

Operator Description Example

[] 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

+ It concatenates 2 strings It concatenate strings and gives the result x="Python"


y="99"
print x+y
* Repeat It prints the character twice. x="Python"
y="99"
print x*2

Some more examples

You can update Python String by re-assigning a variable to another string.


The new value can be related to previous value or to a completely different
string all together.

x = "Hello World!"
print(x[:6])
print(x[0:6] + "Python99")

Note : - Slice:6 or 0:6 has the same effect

Python String replace() Method

The method replace() returns a copy of the string in which the values of old
string have been replaced with the new value.

oldstring = 'I like Python99'


newstring = oldstring.replace('like', 'love')
print(newstring)

Changing upper and lower case strings

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

You can also convert your string to lower case

string="PYTHON AT PYTHON99"
print(string.lower())

Using "join" function for the string


The join function is a more flexible way for concatenating string. With join
function, you can add any character into the string.

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.

word="python99 career python99"


print(word.split(' '))

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

word="python99 career python99"


print(word.split('r'))

Important Note:

In Python, Strings are immutable.

Consider the following code

x = "Python99"
x.replace("Python99","Python")
print(x)

will still return Python99. This is because x.replace("Python99","Python")


returns a copy of X with replacements made

You will need to use the following code to observe changes

x = "Python99"
x = x.replace("Python99","Python")
print(x)

Next Topic:- Python TUPLE - Pack, Unpack, Compare, Slicing, Delete,


Key

What is Tuple in Python?


A tuple is just like a list of a sequence of immutable python objects. The
difference between list and tuple is that list are declared in square brackets
and can be changed while tuple is declared in parentheses and cannot be
changed. However, you can take portions of existing tuples to make new
tuples.

Tuple Syntax

Tup = ('Jan','feb','march')

To write an empty tuple, you need to write as two parentheses containing


nothing-

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

Here is the code,


tup1 = ('Robert', 'Carlos','1965','Terminator 1995', 'Actor','Florida');
tup2 = (1,2,3,4,5,6,7);
print(tup1[0])
print(tup2[1:4])

 Tuple 1 includes list of information of Robert


 Tuple 2 includes list of numbers in it
 We call the value for [0] in tuple and for tuple 2 we call the value
between 1 and 4
 Run the code- It gives name Robert for first tuple while for second tuple
it gives number (2,3 and 4)

Packing and Unpacking


In packing, we place value into a new tuple while in unpacking we extract
those values back into variables.

x = ("Python", 20, "Education") # tuple packing


(company, emp, profile) = x # tuple unpacking
print(company)
print(emp)
print(profile)

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

Let's study this with an example-

#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."

Using tuples as keys in dictionaries


Since tuples are hashable, and list is not, we must use tuple as the key if we
need to create a composite key to use in a dictionary.

Example: We would come across a composite key if we need to create a


telephone directory that maps, first-name, last-name, pairs of telephone
numbers, etc. Assuming that we have declared the variables as last and first
number, we could write a dictionary assignment statement as shown below:

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.

for last, first in directory:


print first, last, directory[last, first]
This loop navigates the keys in the directory, which are tuples. It assigns the
elements of each tuple to last and first and then prints the name and
corresponding telephone number.

Tuples and 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.

x = ("a", "b","c", "d", "e")


print(x[2:4])

The output of this code will be ('c', 'd').

Built-in functions with Tuple


To perform different task, tuple allows you to use many built-in
functions like all(), any(), enumerate(), max(), min(), sorted(), len(),
tuple(), etc.
Dictionary
A dictionary is a collection which is unordered, changeable and indexed.
In Python dictionaries are written with curly brackets, and they have keys
and values.

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

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.

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)

Check if Key Exists


To determine if a specified key is present in a dictionary use
the in keyword:

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)

The dict() Constructor


It is also possible to use the dict() constructor to make a new
dictionary:

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)

You might also like