How to Install Python on Windows [Pycharm IDE]
Below are the detailed steps for installing Python and PyCharm
Installing Python
Step 1) To download and install Python visit the official website of Python http://www.python.org/downloads/ and choose your version. We have chosen Python version 3.6.3Step 2) Once the download is complete, run the exe for install Python. Now click on Install Now.
Step 3) You can see Python installing at this point.
Step 4) When it finishes, you can see a screen that says the Setup was successful. Now click on "Close".
Installing Pycharm
Step 1) To download PyCharm visit the website https://www.jetbrains.com/pycharm/download/ and Click the "DOWNLOAD" link under the Community Section.Step 2) Once the download is complete, run the exe for install PyCharm. The setup wizard should have started. Click “Next”.
Step 4) On the next screen, you can create a desktop shortcut if you want and click on “Next”.
Step 5) Choose the start menu folder. Keep selected JetBrains and click on “Install”.
Step 6) Wait for the installation to finish.
Step 7) Once installation finished, you should receive a message screen that PyCharm is installed. If you want to go ahead and run it, click the “Run PyCharm Community Edition” box first and click “Finish”.
Step 8) After you click on "Finish," the Following screen will appear.
Hello World: Create your First Python Program
Creating First Program
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To create a new project, click on “Create New Project”.Step 2) You will need to select a location.
- You can select the location where you want the project to be created. If you don’t want to change location than keep it as it is but at least change the name from “untitled” to something more meaningful, like “FirstProject”.
- PyCharm should have found the Python interpreter you installed earlier.
- Next Click the “Create” Button.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we give “HelloWorld”) and hit “OK”.
Step 5) Now type a simple program - print (‘Hello World!’).
Step 7) You can see the output of your program at the bottom of the screen.
Step 8) Don't worry if you don't have Pycharm Editor installed, you can still run the code from the command prompt. Enter the correct path of a file in command prompt to run the program.
The output of the code would be
Step 9) If you are still not able to run the program, we have Python Editor for you.
Please run the given code at Python Online Editor
print("Hello World")
Python Main Function with Examples: Understand __main__
Consider the following code
def main(): print "hello world!" print "Guru99"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 "Guru99". When you run the function def main ():
- Only "Guru99" prints out
- and not the code "Hello World."
- 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.
- import: __name__= module's filenameif 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."
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("Guru99")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 "Guru99"
In Python 3, you do not need to use if__name. Following code also works
def main(): print("Hello World!") main() print("Guru99")
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.
In this tutorial, we will learn,
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.
Later, we re-assign the variable f to value "guru99"
Python 2 Example
# Declare a variable and initialize it f = 0 print f # re-declaring the variable works f = 'guru99' print fPython 3 Example
# Declare a variable and initialize it f = 0 print(f) # re-declaring the variable works f = 'guru99' print(f)
Concatenate Variables
Let's see whether you can concatenate different data types like string and number together. For example, we will concatenate "Guru" 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="Guru" b = 99 print a+bOnce the integer is declared as string, it can concatenate both "Guru" + str("99")= "Guru99" in the output.
a="Guru" 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.
- Variable "f" is global in scope and is assigned value 101 which is printed in output
- 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
- 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
# Declare a variable and initialize it f = 101 print f # Global vs. local variables in functions def someFunction(): # global f f = 'I am learning Python' print f someFunction() print fPython 3 Example
# Declare a variable and initialize it f = 101 print(f) # Global vs. local variables in functions def someFunction(): # global f f = 'I am learning Python' print(f) someFunction() print(f)Using the keyword global, you can reference the global variable inside a function.
- Variable "f" is global in scope and is assigned value 101 which is printed in output
- 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
- 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"
f = 101; print f # Global vs.local variables in functions def someFunction(): global f print f f = "changing global variable" someFunction() print fPython 3 Example
f = 101; print(f) # Global vs.local variables in functions def someFunction(): global f print(f) f = "changing global variable" someFunction() print(f)
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.
f = 11; print(f) del f print(f)
Summary:
- Variables are referred to "envelop" or "buckets" where information can be maintained and referenced. Like any other programming language Python also uses a variable to store the information.
- Variables can be declared by any name or even alphabets like a, aa, abc, etc.
- Variables can be re-declared even after you have declared it them for once
- In Python you cannot concatenate string with number directly, you need to declare them as a separate variable, and after that, you can concatenate number with string
- Declare local variable when you want to use it for current function
- Declare Global variable when you want to use the same variable for rest of the program
- To delete a variable, it uses keyword "del".
Python Strings: Replace, Join, Split, Reverse, Uppercase & Lowercase
For example:
var = "Hello World!"
In this tutorial, we will learn -
- Accessing Values in Strings
- Various String Operators
- Some more examples
- Python String replace() Method
- Changing upper and lower case strings
- Using "join" function for the string
- Reversing String
- Split Strings
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 = "Guru99!" 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=guru and b=99 then a+b= "guru99". Similarly, if you are using a*2, it will "GuruGuru". Likewise, you can use other operators in string.
Operator | Description | Example | |
---|---|---|---|
[] | Slice- it gives the letter from the given index | a[1] will give "u" from the word Guru as such ( 0=G, 1=u, 2=r and 3=u) | x="Guru" print x[1] |
[ : ] | Range slice-it gives the characters from the given range | x [1:3] it will give "ur" from the word Guru. Remember it will not consider 0 which is G, it will consider word after that is ur. | x="Guru" print x[1:3] |
in | Membership-returns true if a letter exist in the given string | u is present in word Guru and hence it will give 1 (True) | x="Guru" print "u" in x |
not in | Membership-returns true if a letter exist is not in the given string | l not present in word Guru and hence it will give 1 | x="Guru" print "l" not in x |
r/R | Raw string suppresses actual meaning of escape characters. | Print r'\n' prints \n and print R'/n' prints \n | |
% - Used for string format | %r - It insert the canonical string representation of the object (i.e., repr(o)) %s- It insert the presentation string representation of the object (i.e., str(o)) %d- it will format a number for display | The output of this code will be "guru 99". | name = 'guru' number = 99 print'%s %d' % (name,number) |
+ | It concatenates 2 strings | It concatenate strings and gives the result | x="Guru" y="99" print x+y |
* | Repeat | It prints the character twice. | x="Guru" 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] + "Guru99")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 Guru99' 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 guru99" print(string.upper())Likewise, you can also do for other function as well like capitalize
string="python at guru99" print(string.capitalize())You can also convert your string to lower case
string="PYTHON AT GURU99"" 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 "guru99 career guru99". First here we will split the string by using the command word.split and get the result.word="guru99 career guru99" 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="guru99 career guru99" print(word.split('r'))Important Note:
In Python, Strings are immutable.
x = "Guru99" x.replace("Guru99","Python") print(x)will still return Guru99. This is because x.replace("Guru99","Python") returns a copy of X with replacements made
You will need to use the following code to observe changes
x = "Guru99" x = x.replace("Guru99","Python") print(x)Above codes are Python 3 examples, If you want to run in Python 2 please consider following code.
Python 2 Example
#Accessing Values in Strings var1 = "Guru99!" var2 = "Software Testing" print "var1[0]:",var1[0] print "var2[1:5]:",var2[1:5] #Some more examples x = "Hello World!" print x[:6] print x[0:6] + "Guru99" #Python String replace() Method oldstring = 'I like Guru99' newstring = oldstring.replace('like', 'love') print newstring #Changing upper and lower case strings string="python at guru99" print string.upper() string="python at guru99" print string.capitalize() string="PYTHON AT GURU99" print string.lower() #Using "join" function for the string print":".join("Python") #Reversing String string="12345" print''.join(reversed(string)) #Split Strings word="guru99 career guru99" print word.split(' ') word="guru99 career guru99" print word.split('r') x = "Guru99" x.replace("Guru99","Python") print x x = "Guru99" x = x.replace("Guru99","Python") print xPython has introduced a .format function which does way with using the cumbersome %d and so on for string formatting.
Summary:
Since Python is an object-oriented programming language, many functions can be applied to Python objects. A notable feature of Python is its indenting source statements to make the code easier to read.- Accessing values through slicing - square brackets are used for slicing along with the index or indices to obtain a substring.
- In slicing, if range is declared [1:5], it can actually fetch the value from range [1:4]
- You can update Python String by re-assigning a variable to another string
- Method replace() returns a copy of the string in which the occurrence of old is replaced with new.
- Syntax for method replace: oldstring.replace("value to change","value to be replaced")
- String operators like [], [ : ], in, Not in, etc. can be applied to concatenate the string, fetching or inserting specific characters into the string, or to check whether certain character exist in the string
- Other string operations include
- Changing upper and lower case
- Join function to glue any character into the string
- Reversing string
- Split string
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.
In this tutorial, we will learn-
- Packing and Unpacking
- Comparing tuples
- Using tuples as keys in dictionaries
- Deleting Tuples
- Slicing of Tuple
- Built-in functions with Tuple
- Advantages of tuple over list
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 = ("Guru99", 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
#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] = numberInside 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
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').
Here is the Python 2 Code for all above example
tup1 = ('Robert', 'Carlos','1965','Terminator 1995', 'Actor','Florida'); tup2 = (1,2,3,4,5,6,7); print tup1[0] print tup2[1:4] #Packing and Unpacking x = ("Guru99", 20, "Education") # tuple packing (company, emp, profile) = x # tuple unpacking print company print emp print profile #Comparing 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" #Tuples and dictionary a = {'x':100, 'y':200} b = a.items() print b #Slicing of Tuple x = ("a", "b","c", "d", "e") print x[2:4]
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.Advantages of tuple over list
- Iterating through tuple is faster than with list, since tuples are immutable.
- Tuples that consist of immutable elements can be used as key for dictionary, which is not possible with list
- If you have data that is immutable, implementing it as tuple will guarantee that it remains write-protected
Python has tuple assignment feature which enables you to assign more than one variable at a time.
- Packing and Unpacking of Tuples
- In packing, we place value into a new tuple while in unpacking we extract those values back into variables.
- A comparison operator in Python can work with tuples.
- Using tuples as keys in dictionaries
- Tuples are hashable, and list are not
- We must use tuple as the key if we need to create a composite key to use in a dictionary
- Dictionary can return the list of tuples by calling items, where each tuple is a key value pair
- Tuples are immutable and cannot be deleted, but deleting tuple entirely is possible by using the keyword "del."
- To fetch specific sets of sub-elements from tuple or list, we use this unique function called slicing
Python Dictionary(Dict): Update, Cmp, Len, Sort, Copy, Items, str Example
- Keys will be a single element
- Values can be a list or list within a list, numbers, etc.
- Python Dictionary Methods
- Copying dictionary
- Updating Dictionary
- Delete Keys from the dictionary
- Dictionary items() Method
- Sorting the Dictionary
- Python Dictionary in-built Functions
- Dictionary len() Method
- Variable Types
- Python List cmp() Method
- Dictionary Str(dict)
Dict = { ' Tim': 18, xyz,.. }Dictionary is listed in curly brackets, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:) while each element is separated by commas.
Properties of Dictionary Keys
There are two important points while using dictionary keys
- More than one entry per key is not allowed ( no duplicate key is allowed)
- The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.
- Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries.
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print (Dict['Tiffany'])Python 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print((Dict['Tiffany']))
- In code, we have dictionary name "Dict"
- We declared the name and age of the person in the dictionary, where name is "Keys" and age is the"value"
- Now run the code
- It retrieves the age of tiffany from the dictionary.
Python Dictionary Methods
Copying dictionary
You can also copy the entire dictionary to new dictionary. For example, here we have copied our original dictionary to new dictionary name "Boys" and "Girls".Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} studentX=Boys.copy() studentY=Girls.copy() print studentX print studentYPython 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} studentX=Boys.copy() studentY=Girls.copy() print(studentX) print(studentY)
- We have the original dictionary (Dict) with the name and age of the boys and girls together
- But we want boys list separate from girls list, so we defined the element of boys and girls in a separate dictionary name "Boys" and "Girls."
- Now again we have created new dictionary name "studentX" and "studentY", where all the keys and values of boy dictionary are copied into studentX, and the girls will be copied in studentY
- So now you don't have to look into the whole list in main dictionary( Dict) to check who is boy and who is girl, you just have to print studentX if you want boys list and StudentY if you want girls list
- So, when you run the studentX and studentY dictionary, it will give all the element present in the dictionary of "boys" and "girls" separately
Updating Dictionary
You can also update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. Here in the example we will add another name "Sarah" to our existing dictionary.Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Dict.update({"Sarah":9}) print DictPython 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Dict.update({"Sarah":9}) print(Dict)
- Our existing dictionary "Dict" does not have the name "Sarah."
- We use the method Dict.update to add Sarah to our existing dictionary
- Now run the code, it adds Sarah to our existing dictionary
Delete Keys from the dictionary
Python dictionary gives you the liberty to delete any element from the dictionary list. Suppose you don't want the name Charlie in the list, so you can delete the key element by following code.Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} del Dict ['Charlie'] print DictPython 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} del Dict ['Charlie'] print(Dict)When you run this code, it should print the dictionary list without Charlie.
- We used the code del Dict
- When code executed, it has deleted the Charlie from the main dictionary
Dictionary items() Method
The items() method returns a list of tuple pairs (Keys, Value) in the dictionary.Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print "Students Name: %s" % Dict.items()Python 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("Students Name: %s" % list(Dict.items()))
- We use the code items() method for our Dict.
- When code was executed, it returns a list of items ( keys and values) from the dictionary
For a given list, you can also check whether our child dictionary exists in a main dictionary or not. Here we have two sub-dictionaries "Boys" and "Girls", now we want to check whether our dictionary Boys exist in our main "Dict" or not. For that, we use the forloop method with else if method.
Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} for key in Dict.keys(): if key in Boys.keys(): print True else: print FalsePython 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} for key in list(Dict.keys()): if key in list(Boys.keys()): print(True) else: print(False)
- The forloop in code checks each key in the main dictionary for Boys keys
- If it exists in the main dictionary, it should print true or else it should print false
- When you execute the code, it will print "True" for three times, as we got three elements in our "Boys" dictionary
- So it indicates that the "Boys" exist in our main dictionary (Dict)
Sorting the Dictionary
In the dictionary, you can also sort the elements. For example, if we want to print the name of the elements of our dictionary alphabetically we have to use the forloop. It will sort each element of dictionary accordingly.Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} Students = Dict.keys() Students.sort() for S in Students: print":".join((S,str(Dict[S])))Python 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} Students = list(Dict.keys()) Students.sort() for S in Students: print(":".join((S,str(Dict[S]))))
- We declared the variable students for our dictionary "Dict."
- Then we use the code Students.sort, which will sort the element inside our dictionary
- But to sort each element in dictionary, we run the forloop by declaring variable S
- Now, when we execute the code the forloop will call each element from the dictionary, and it will print the string and value in an order
Python Dictionary in-built Functions
Dictionary len() Method
The len() function gives the number of pairs in the dictionary.For example,
Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print "Length : %d" % len (Dict)Python 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("Length : %d" % len (Dict))When len (Dict) function is executed it gives the output at "4" as there are four elements in our dictionary
Variable Types
Python does not require to explicitly declare the reserve memory space; it happens automatically. The assign values to variable "=" equal sign are used. The code to determine the variable type is " %type (Dict)."Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print "variable Type: %s" %type (Dict)Python 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("variable Type: %s" %type (Dict))
- Use the code %type to know the variable type
- When code was executed, it tells a variable type is a dictionary
Python List cmp() Method
The compare method cmp() is used in Python to compare values and keys of two dictionaries. If method returns 0 if both dictionaries are equal, 1 if dic1 > dict2 and -1 if dict1 < dict2.Python 2 Example
Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} print cmp(Girls, Boys)Python 3 Example
cmp is not supported in Python 3
- We have two dictionary name "Boys" and "Girls."
- Which ever you declare first in code "cmp(Girls, Boys)" will be considered as dictionary 1. In our case, we declared "Girls" first, so it will be considered as dictionary 1 and boys as dictionary 2
- When code is executed it prints out -1, It indicates that our dictionary 1 is less than dictionary 2.
Dictionary Str(dict)
With Str() method, you can make a dictionary into a printable string format.Python 2 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print "printable string:%s" % str (Dict)Python 3 Example
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("printable string:%s" % str (Dict))
- Use the code % str (Dict)
- It will return the dictionary elements into a printable string format
Method | Description | Syntax |
---|---|---|
copy() | Copy the entire dictionary to new dictionary | dict.copy() |
update() | Update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. | Dict.update([other]) |
items() | Returns a list of tuple pairs (Keys, Value) in the dictionary. | dictionary.items() |
sort() | You can sort the elements | dictionary.sort() |
len() | Gives the number of pairs in the dictionary. | len(dict) |
cmp() | Compare values and keys of two dictionaries | cmp(dict1, dict2) |
Str() | Make a dictionary into a printable string format | Str(dict) |
Summary:
Dictionaries in a programming language is a type of data-structure used to store information connected in someway. Python Dictionary are defined into two elements Keys and Values. Dictionaries do not store their information in any particular order, so you may not get your information back in the same order you entered it.- Keys will be a single element
- Values can be a list or list within a list, numbers, etc.
- More than one entry per key is not allowed ( no duplicate key is allowed)
- The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.
- Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries.
Python Operators: Arithmetic, Logical, Comparison, Assignment, Bitwise & Precedence
In this tutorial, we going to learn various operators
- Arithmetic Operators
- Comparison Operators
- Python Assignment Operators
- Logical Operators or Bitwise Operators
- Membership Operators
- Identity Operators
- Operator precedence
Arithmetic Operators
Arithmetic Operators perform various arithmetic calculations like addition, subtraction, multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic calculation in Python like you can use the eval function, declare variable & calculate, or call functions.Example: For arithmetic operators we will take simple example of addition where we will add two-digit 4+5=9
x= 4 y= 5 print(x + y)Similarly, you can use other arithmetic operators like for multiplication(*), division (/), substraction (-), etc.
Comparison Operators
These operators compare the values on either side of the operand and determine the relation between them. It is also referred as relational operators. Various comparison operators are ( ==, != , <>, >,<=, etc)Example: For comparison operators we will compare the value of x to the value of y and print the result in true or false. Here in example, our value of x = 4 which is smaller than y = 5, so when we print the value as x>y, it actually compares the value of x to y and since it is not correct, it returns false.
x = 4 y = 5 print(('x > y is',x>y))Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)
Python Assignment Operators
Python assignment operators are used for assigning the value of the right operand to the left operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.)Example: Python assignment operators is simply to assign the value, for example
num1 = 4 num2 = 5 print(("Line 1 - Value of num1 : ", num1)) print(("Line 2 - Value of num2 : ", num2))Example of compound assignment operator
We can also use a compound assignment operator, where you can add, subtract, multiply right operand to left and assign addition (or any other arithmetic function) to the left operand.
- Step 1: Assign value to num1 and num2
- Step 2: Add value of num1 and num2 (4+5=9)
- Step 3: To this result add num1 to the output of Step 2 ( 9+4)
- Step 4: It will print the final result as 13
num1 = 4 num2 = 5 res = num1 + num2 res += num1 print(("Line 1 - Result of + is ", res))
Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators in Python are AND, OR and NOT. For logical operators following condition are applied.- For AND operator – It returns TRUE if both the operands (right side and left side) are true
- For OR operator- It returns TRUE if either of the operand (right side or left side) is true
- For NOT operator- returns TRUE if operand is false
a = True b = False print(('a and b is',a and b)) print(('a or b is',a or b)) print(('not a is',not a))
Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples. There are two membership operators that are used in Python. (in, not in). It gives the result based on the variable present in specified sequence or stringExample: For example here we check whether the value of x=4 and value of y=8 is available in list or not, by using in and not in operators.
x = 4 y = 8 list = [1, 2, 3, 4, 5 ]; if ( x in list ): print("Line 1 - x is available in the given list") else: print("Line 1 - x is not available in the given list") if ( y not in list ): print("Line 2 - y is not available in the given list") else: print("Line 2 - y is available in the given list")
- Declare the value for x and y
- Declare the value of list
- Use the "in" operator in code with if statement to check the value of x existing in the list and print the result accordingly
- Use the "not in" operator in code with if statement to check the value of y exist in the list and print the result accordingly
- Run the code- When the code run it gives the desired output
Identity Operators
To compare the memory location of two objects, Identity Operators are used. The two identify operators used in Python are (is, is not).- Operator is: It returns true if two variables point the same object and false otherwise
- Operator is not: It returns false if two variables point the same object and true otherwise
Operators (Decreasing order of precedence) | Meaning |
---|---|
** | Exponent |
*, /, //, % | Multiplication, Division, Floor division, Modulus |
+, - | Addition, Subtraction |
<= < > >= | Comparison operators |
= %= /= //= -= += *= **= | Assignment Operators |
is is not | Identity operators |
in not in | Membership operators |
not or and | Logical operators |
x = 20 y = 20 if ( x is y ): print("x & y SAME identity") y=30 if ( x is not y ): print("x & y have DIFFERENT identity")
- Declare the value for variable x and y
- Use the operator "is" in code to check if value of x is same as y
- Next we use the operator "is not" in code if value of x is not same as y
- Run the code- The output of the result is as expected
Operator precedence
The operator precedence determines which operators need to be evaluated first. To avoid ambiguity in values, precedence operators are necessary. Just like in normal multiplication method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the answer is 23, to change the order of precedence we use a parentheses (3+4)*5, now the answer is 35. Precedence operator used in Python are (unary + - ~, **, * / %, + - , &) etc.v = 4 w = 5 x = 8 y = 2 z = 0 z = (v+w) * x / y; print("Value of (v+w) * x/ y is ", z)
- Declare the value of variable v,w…z
- Now apply the formula and run the code
- The code will execute and calculate the variable with higher precedence and will give the output
Python 2 Example
Above examples are Python 3 codes, if you want to use Python 2, please consider following codes#Arithmetic Operators x= 4 y= 5 print x + y #Comparison Operators x = 4 y = 5 print('x > y is',x>y) #Assignment Operators num1 = 4 num2 = 5 print ("Line 1 - Value of num1 : ", num1) print ("Line 2 - Value of num2 : ", num2) #compound assignment operator num1 = 4 num2 = 5 res = num1 + num2 res += num1 print ("Line 1 - Result of + is ", res) #Logical Operators a = True b = False print('a and b is',a and b) print('a or b is',a or b) print('not a is',not a) #Membership Operators x = 4 y = 8 list = [1, 2, 3, 4, 5 ]; if ( x in list ): print "Line 1 - x is available in the given list" else: print "Line 1 - x is not available in the given list" if ( y not in list ): print "Line 2 - y is not available in the given list" else: print "Line 2 - y is available in the given list" #Identity Operators x = 20 y = 20 if ( x is y ): print "x & y SAME identity" y=30 if ( x is not y ): print "x & y have DIFFERENT identity" #Operator precedence v = 4 w = 5 x = 8 y = 2 z = 0 z = (v+w) * x / y; print "Value of (v+w) * x/ y is ", z
Summary:
Operators in a programming language are used to perform various operations on values and variables. In Python, you can use operators like- There are various methods for arithmetic calculation in Python as you can use the eval function, declare variable & calculate, or call functions
- Comparison operators often referred as relational operators are used to compare the values on either side of them and determine the relation between them
- Python assignment operators are simply to assign the value to variable
- Python also allows you to use a compound assignment operator, in a complicated arithmetic calculation, where you can assign the result of one operand to the other
- For AND operator – It returns TRUE if both the operands (right side and left side) are true
- For OR operator- It returns TRUE if either of the operand (right side or left side) is true
- For NOT operator- returns TRUE if operand is false
- There are two membership operators that are used in Python. (in, not in).
- It gives the result based on the variable present in specified sequence or string
- The two identify operators used in Python are (is, is not)
- It returns true if two variables point the same object and false otherwise
- Precedence operator can be useful when you have to set priority for which calculation need to be done first in a complex calculation.
No comments:
Post a Comment