{"id":3958,"date":"2023-08-05T10:23:46","date_gmt":"2023-08-05T10:23:46","guid":{"rendered":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/?post_type=blog&#038;p=3958"},"modified":"2023-10-01T06:42:01","modified_gmt":"2023-10-01T06:42:01","slug":"top-7-tricks-to-write-better-python-code","status":"publish","type":"blog","link":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/blog\/top-7-tricks-to-write-better-python-code\/","title":{"rendered":"Write Better Python Code with These 07 Tricks"},"content":{"rendered":"\n<h3>Introduction<\/h3>\n<p>\n\n\t<a href=\"https:\/\/www.credosystemz.com\/training-in-chennai\/best-python-training-in-chennai\/\">Python<\/a> is one of the popular programming languages for beginners to learn with a rise in interest by 27% from the previous year according to O&#8217;Reillyreport. <strong>Learning python<\/strong> coding is fun because the same functionalities can be achieved in many different ways. Anyone can learn Python and become a Python Developer with practice.\n\t\t\n<\/p>\n\n<h3>Indexing<\/h3>\nIn python, we have compound datatypes to store multiple items of different type of data, such as,\n\n<ul class=\"list\">\n<li>List<\/li>\n<li>Tuple<\/li>\n<li>Set<\/li>\n\t<li>Dictionary<\/li>\n<\/ul>\n\nTo access individual items in compound data types, we can use indexing using a numerical index in square brackets. Like other main stream programming languages, <strong>Python<\/strong> supports 0-based indexing, where we access the first element using zero within a pair of square brackets.\n<br><br>\n<strong>Program<\/strong>\n\t<pre><code>\n# Positive Indexing\nalphabet = [a,b,c,d,e,f,g]\nprint(\"First Alphabet:\", alphabet[0])\nprint(\"First Four Alphabet :\", alphabet [:4])\nprint(\"Odd Alphabet:\", alphabet [::2])\n<\/code><\/pre>\n<strong>Output<\/strong>\nFirst Alphabet: a<br><br>\nFirst Four Numbers: [a, b, c, d]<br><br>\nOdd Numbers: [a, c, e, g]\n<p>\nPython also support negative indexing in which -1 refers to the last element in the sequence and using that we can count the items backward. For example, the last but one element has an index of -2 and so on. Importantly, the negative indexing can also work with the positive index in the slice object.\n\t\t<\/p>\n\t\n<strong>Program<\/strong>\n\t<pre><code>\n# Negative Indexing\nvalues= (10, 40, 4)\nnames = [\"Priya\", \"Anu\", \"Rajkumar\", \"Danny\"]\nprint(values[-1])\nprint(names[-3:-1])\n<\/code><\/pre>\n\n<strong>Output<\/strong><br><br>\n4<br><br>\n[&#8216;Anu&#8217;, &#8216;Rajkumar&#8217;]\n\n<h3>List of Strings creation <\/h3>\n\nStrings are identifiers for storing sequence of characters and individual characters of a String can be accessed by using the method of Indexing. To create list of strings use\nCompound datatypes like list<br><br>\nsplit() method<br><br>\nThe split () method breaks the given string into multiple strings at the specified separator arranges them in a list and returns the list.\n<strong>Program<\/strong>\n\t<pre><code>\ntext = 'Python for all'\nprint(text.split(' '))\n<\/code><\/pre>\n\n<strong>Output <\/strong>\n<p>\n[&#8216;Python&#8217;, &#8216;for&#8217;, &#8216;all&#8217;]<br><br>\nAs shown above,by default the split() method uses the spaces as the separators and creates a list of strings from the given string. We can use a different kind of separator like commas to create a list of strings with some elements containing spaces.\n\t<\/p>\n\n<strong>Program<\/strong>\n\t<pre><code>\ntxt = \u2018hello, how r u, glad to meet you\u2019\nx = txt.split(\", \",4)\nprint(x)\n<\/code><\/pre>\n\n<strong>Output<\/strong>\n\n<p>\n[\u2018hello\u2019,\u2019how r u\u2019,\u2019glad to meet you]<br><br>\n&#8220;, &#8220;- separator<br><br>\n4- maxsplit\n<br><br>\nThe separator,maxsplit are the two parameters used in the split() method to specify where the splits occur and the maximum number of splits. These parameters are optional. If the parameter values are not provided, the string splits at whitespaces and no limit on the number of splits.\n\t<\/p>\n\n<h3>Ternary Expression<\/h3>\n\nTo check condition or todefine variables with particular condition, we use control flow statements like if\u2026else statement <br><br>\n<strong>Program<\/strong>\n\t<pre><code>\nif mark >90\nreward=\u2019excellent\u2019\nelse:\nreward=\u2019good\u2019\n<\/code><\/pre>\nWe can use ternary expression to check the condition while dealing with assignment of one variable with few lines of code.<br><br>\nThe syntax for the ternary operator in Python is:<br><br>\n[on_true] if [expression] else [on_false]<br><br>\nLet\u2019s rewrite the above code using ternary operator,<br><br>\nreward=\u2019excellent\u2019 if mark>90 else reward=\u2019good\u2019\n\n<h2>Learn Python and Certified \u2013 <a title=\"Python Training in Chennai\" href=\"https:\/\/www.credosystemz.com\/training-in-chennai\/best-python-training-in-chennai\/\">Get Your Certification<\/a><\/h2>\n\n<h3>With Statement for File Object<\/h3>\n\nWe can read data from files and write data to files. To open a file use the built-in open() function, which creates a file object that can operate. Let\u2019s see the below scenario,<br><br>\nCreate a text file that has the text: Hello World!<br><br>\nClose the file<br><br>\nOpen the file and append new data<br><br>\nClose the file<br><br>\nIf we don\u2019t close the file after any changes like writing new data, editing new data, the changes won\u2019t be saved. We can do this using the \u201cwith\u201d statement, which will close the file for us automatically. \n<strong>Program<\/strong>\n\t<pre><code>\nwith open(\"hello_world.txt\", \"a\") as file:\nfile.write(\"Hello Python!\")\nwith open(\"hello_world.txt\") as file:\n    print(file.read())\nprint(\"Is file close?\", file.closed)\n<\/code><\/pre>\nHello World!HelloPython!Hello Python!<br><br>\nIs file close? True<br><br>\nUsing the with statement,the file gets closed automatically.\n<h2 class=\"left-border\">Evaluate Multiple Conditions<\/h2>\nThere are several possible scenariosto evaluate multiple conditions. We can have multiple comparisons for the same variable for numeric values.\n\t<pre><code>\nif x < 5 and x> 1:\n    pass\nif 1 < x < 5:\n    pass\nUse the in keyword to have multiple equality comparisons:\nif a == \"Jan\" or a == \"Feb\" or a == \"Mar\" :\npass\nif b in \"Jan Feb Mar\".split():\npass\n<\/code><\/pre>\n\nUse the built-in functionsall() and any()  for evaluating multiple conditions. The all() function will evaluate to be True when the elements are all True, and suitable to replace a series of AND logical comparisons. On the other hand, the any() function will evaluate to be True when any element is True, and suitable to replace a series of OR logical operations. <br><br>\n\n<h3>Use Default Values in Function Declarations<\/h3>\n<p>\nMost of the python projects involve creating and calling functions multiple times whenever needed. Functions are used to implement program logic to execute repeatedly at different places in the code. Arguments are used to pass data to these functions and default argument values can be used in Python functions. Parameters are the values passed to the function arguments and operate depending on the parameters. \n<\/p>\n\n<strong>Syntax<\/strong><br><br>\n\ndeffunction_name(param1=value1, param2, param3)\n\n\t<h2 class=\"left-border\">Sorting With Different Order Requirements<\/h2>\n\t<p>\nSorting is essential utility for any programming language. The basic sorting is based on the numeric order, and can use the built-in sorted() function. The sorted() function will sort the list in the ascending order. If we specify the reverse argument to be True, we can get the items in the descending order. \n\t\t<\/p>\n\t\n<strong>Program<\/strong>\n\t\t<pre><code>\n# A list of numbers and strings\nnumbers = [1, 3, 5, 2, 6, 4]\nwords = ['orange', 'apple', 'papaya', 'mango']\n# Sort them\nprint(sorted(numbers))\nprint(sorted(words))\n<\/code><\/pre>\n\n<strong>Output<\/strong>\n<p>\n[1, 2, 3, 4, 5, 6]<br><br>\n['apple', 'mango', 'orange', 'papaya']\n<\/p>\n\n<strong>Program<\/strong>\n\t<pre><code>\n# Sort them in descending order\nprint(sorted(numbers, reverse=True))\nprint(sorted(words, reverse=True))\n<\/code><\/pre>\n\n<strong>Output:<\/strong>\n\t<p>\n[6, 5, 4, 3, 2, 1]<br><br>\n[ 'papaya', 'orange', 'mango', 'apple']\n\t<\/p>\n\t\n\t<h3>Conclusion<\/h3>\n\t\n\t<p>\n\t\tTo conclude, this article clearly explains the few important tricks to Write Better Python Code with easy explanation. To know more and learn with the help of professional expert trainers: <a href=\"https:\/\/www.credosystemz.com\/training-in-chennai\/best-python-training-in-chennai\/\">Python Certification course with Placements<\/a>\n\t<\/p>\n","protected":false},"featured_media":7827,"template":"","tags":[],"class_list":["post-3958","blog","type-blog","status-publish","has-post-thumbnail","hentry"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>IT Training Institute in chennai | Best Placement Training Institute<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:site_name\" content=\"IT Training Institute in chennai | Best Placement Training Institute\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"CollectionPage\",\"@id\":null,\"url\":\"\",\"name\":\"\",\"isPartOf\":{\"@id\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#website\"},\"breadcrumb\":{\"@id\":\"#breadcrumb\"},\"inLanguage\":\"en-US\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"#breadcrumb\",\"itemListElement\":[]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#website\",\"url\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/\",\"name\":\"IT Training Institute in chennai | Best Placement Training Institute\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#organization\",\"name\":\"IT Training Institute in chennai | Best Placement Training Institute\",\"url\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-content\/uploads\/2023\/01\/logo.png\",\"contentUrl\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-content\/uploads\/2023\/01\/logo.png\",\"width\":323,\"height\":50,\"caption\":\"IT Training Institute in chennai | Best Placement Training Institute\"},\"image\":{\"@id\":\"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#\/schema\/logo\/image\/\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"IT Training Institute in chennai | Best Placement Training Institute","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"og_locale":"en_US","og_type":"article","og_site_name":"IT Training Institute in chennai | Best Placement Training Institute","twitter_card":"summary_large_image","schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"CollectionPage","@id":null,"url":"","name":"","isPartOf":{"@id":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#website"},"breadcrumb":{"@id":"#breadcrumb"},"inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"#breadcrumb","itemListElement":[]},{"@type":"WebSite","@id":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#website","url":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/","name":"IT Training Institute in chennai | Best Placement Training Institute","description":"","publisher":{"@id":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#organization","name":"IT Training Institute in chennai | Best Placement Training Institute","url":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#\/schema\/logo\/image\/","url":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-content\/uploads\/2023\/01\/logo.png","contentUrl":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-content\/uploads\/2023\/01\/logo.png","width":323,"height":50,"caption":"IT Training Institute in chennai | Best Placement Training Institute"},"image":{"@id":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/#\/schema\/logo\/image\/"}}]}},"_links":{"self":[{"href":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-json\/wp\/v2\/blog\/3958","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-json\/wp\/v2\/blog"}],"about":[{"href":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-json\/wp\/v2\/types\/blog"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-json\/wp\/v2\/media\/7827"}],"wp:attachment":[{"href":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-json\/wp\/v2\/media?parent=3958"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webinfy.in\/demo\/credosystemz.com\/wp-json\/wp\/v2\/tags?post=3958"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}