![]() |
VOOZH | about |
Python is one of the most widely-used and popular programming languages, was developed by Guido van Rossum and released first in 1991. Python is a free and open-source language with a very simple and clean syntax which makes it easy for developers to learn Python. It supports object-oriented programming and is most commonly used to perform general-purpose programming.
Table of Content
To master python from scratch, you can refer to our article: Python Tutorial
print() function in Python is used to print Python objects as strings as standard output. keyword end can be used to avoid the new line after the output or end the output with a different string.
Python sep parameter in print()
The separator between the inputs to the print() method in Python is by default a space, however, this can be changed to any character, integer, or string of our choice. The 'sep' argument is used to do the same thing.
input() method in Python is used to accept user input. By default, it returns the user input as a string. By default, the input() function accepts user input as a string.
Output:
Enter your value: Hello Geeks
Hello GeeksComments in Python are the lines in the code that are ignored by the interpreter during the execution of the program. There are three types of comments in Python:
geeksforgeeks
Variables store values and Python supports multiple data types.
We can check the data type of a variable using type() and convert types if needed.
In general, Operators are used to execute operations on values and variables. These are standard symbols used in logical and mathematical processes.
Used to execute different blocks of code based on conditions.
Loops help iterate over sequences or repeat actions.
For Loop:
While Loop:
Loop Control Statements include break and continue.
break exits the loop, while continue skips the current iteration.
Interesting Facts about Loops in Python:
1. Using enumerate to Get Index and Value in a Loop: Want to find the index inside a for loop? Wrap an iterable with ‘enumerate’ and it will yield the item along with its index. See this code snippet
0 a 1 e 2 i 3 o 4 u
Python Functions are a collection of statements that serve a specific purpose. The idea is to bring together some often or repeatedly performed actions and construct a function so that we can reuse the code included in it rather than writing the same code for different inputs over and over.
Welcome to GFG
Arguments are the values given between the function's parenthesis. A function can take as many parameters as it wants, separated by commas.
even odd
The function return statement is used to terminate a function and return to the function caller with the provided value or data item.
Result of add function is 5 Result of is_true function is True
The Python range() function returns a sequence of numbers, in a given range.
0 1 2 3 4
The *args and **kwargs keywords allow functions to take variable-length parameters. The number of non-keyworded arguments and the action that can be performed on the tuple are specified by the *args.**kwargs, on the other hand, pass a variable number of keyword arguments dictionary to function, which can then do dictionary operations.
arg1: Geeks arg2: for arg3: Geeks arg1: Geeks arg2: for arg3: Geeks
Interesting Facts about Functions in Python:
1. One can return multiple values in Python: In Python, we can return multiple values from a function. Python allows us to return multiple values by separating them with commas. These values are implicitly packed into a tuple and when the function is called, the tuple is returned
1 2 3 4 5
Python list is a sequence data type that is used to store the collection of data. Tuples and String are other types of sequence data types.
['Geeks', 'for', 'Geeks']
List comprehension
A Python list comprehension is made up of brackets carrying the expression, which is run for each element, as well as the for loop, which is used to iterate over the Python list's elements.
Also, Read - Python Array
[1, 2, 3]
Interesting Facts about Lists in Python
Explore in detail about Interesting Facts About Python Lists
A dictionary in Python is a collection of key values, used to store data values like a map, which, unlike other data types holds only a single value as an element.
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehension. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Interesting Facts About Python Dictionary
Explore in detail about Interesting Facts About Python Dictionary
Tuple is a list-like collection of Python objects. A tuple stores a succession of values of any kind, which are indexed by integers.
('Geeks', 'for', 'Geeks')
Python Set is an unordered collection of data types that can be iterated, mutated and contains no duplicate elements. The order of the elements in a set is unknown, yet it may contain several elements.
{'for', 'Geeks'}
In Python, a string is a data structure that represents a collection of characters. A string cannot be changed once it has been formed because it is an immutable data type.
Creating and Accessing String
Strings in Python can be created using single quotes or double quotes or even triple quotes. In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing allows negative address references to access characters from the back of the String.
Initial String: GeeksForGeeks First character of String is: G Last character of String is: s
String Slicing
Strings in Python can be constructed with single, double, or even triple quotes. The slicing method is used to access a single character or a range of characters in a String. A Slicing operator (colon) is used to slice a String.
Initial String: GeeksForGeeks Slicing characters from 3-12: k Slicing characters between 3rd and 2nd last character: ksForGee
Interesting Facts About Python strings
Explore in detail about Interesting Facts about Python Strings
Explore in Detail Python Data Structures and Algorithms
There are numerous built-in methods in Python that make creating code easier. Learn about the built-in functions of Python in this post as we examine their numerous uses and highlight a few of the most popular ones.
For More Read, refer Python Built in Functions
Object-oriented Programming (OOPs) is a programming paradigm in Python that employs objects and classes. It seeks to include real-world entities such as inheritance, polymorphisms, encapsulation and so on into programming. The primary idea behind OOPs is to join the data and the functions that act on it as a single unit so that no other portion of the code can access it.
In this example, we have a Car class with characteristics that represent the car's make, model and year. The _make attribute is protected with a single underscore _. The __model attribute is marked as private with two underscores __. The year attribute is open to the public.
We can use the getter function get_make() to retrieve the protected attribute _make. We can use the setter method set_model() to edit the private attribute __model. Using the getter method get_model(), we may retrieve the changed private attribute __model. There are no restrictions on accessing the public attribute year. We manage the visibility and accessibility of class members by using encapsulation with private and protected properties, offering a level of data hiding and abstraction.
Toyota Camry 2022
Interesting facts about OOPs in Python:
1. Python Supports Multiple Programming Paradigms: One of Python's key strengths is its flexibility. Python supports several programming paradigms, including:
2. Everything in Python Is an Object: In Python, everything is an object, including data types such as integers, strings and functions. This allows for object-oriented programming (OOP) principles to be applied across all aspects of the language, including the ability to define classes, inheritance and methods.
<class 'int'> <class 'function'>
We define a pattern using a regular expression to match email addresses. The pattern r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b" is a common pattern for matching email addresses. Using the re.search() function, the pattern is then found in the given text. If a match is found, we use the match object's group() method to extract and print the matched email. Otherwise, a message indicating that no email was found is displayed.
Found email: example@example.com
MetaCharacters are helpful, significant and will be used in module re functions, which helps us comprehend the analogy with RE. The list of metacharacters is shown below.
For More RegEx example, refer to Python RegEx.
In Python, Try and except statements are used to catch and manage exceptions. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
Second element = 2 An error occurred
Debugging is the process of finding and fixing errors (bugs) in our code. Python provides several methods and tools to help debug programs effectively.
x: 10 y: 20 result: 30
The pdb module provides an interactive debugging environment. We can set breakpoints, step through the code, inspect variables and more. To start debugging, insert pdb.set_trace() where we want to start the debugger.
Output
> /home/repl/2b752c75-c2c1-44d7-b2bd-fa43a3072b3c/main.py(6)<module>()
-> result = x + y
(Pdb)Once the program reaches pdb.set_trace(), it will enter the interactive mode where we can run various commands like:
The logging module is more advanced than print() statements and is useful for debugging in production environments. It allows us to log messages with different severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).
Output
DEBUG:root:This is a debug message
INFO:root:This is an info message
WARNING:root:This is a warning message
ERROR:root:This is an error message
CRITICAL:root:This is a critical messagePython too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.
File example.txt created successfully. Hello, world! Text appended to file example.txt successfully. Hello, world! This is some additional text. File example.txt renamed to new_example.txt successfu...
Python provides built-in functions to handle file operations such as reading from and writing to files. We can use the open() function to work with files.
1. Opening a File:
The open() function is used to open a file and returns a file object.
2. Reading from a File:
There are several methods to read the contents of a file:
3. Writing to a File:
We can write data to a file using the write() or writelines() methods:
write(): Writes a string to the file.
writelines(): Writes a list of strings to the file.
4. Closing the File:
It is good practice to close the file after operations using file.close(), but it is recommended to use the with statement as it automatically handles file closure.
Memory management in Python is handled by the Python memory manager. Python uses an automatic memory management system, which includes garbage collection to reclaim unused memory and reference counting to track memory usage.
Memory size of x: 28 Memory size of y: 88 3
Decorators are used to modifying the behavior of a function or a class. They are usually called before the definition of a function we want to decorate.
It is used to set the property 'name'
It is used to delete the property 'name'
Libraries in Python are collections of pre-written code that allow us to perform common tasks without having to write everything from scratch. They provide functions and classes to help with tasks like data manipulation, web scraping and machine learning. Python has a vast ecosystem of libraries, both built-in and third-party.
These libraries are part of Python's standard library and come bundled with Python installation. Some Basic Libraries are:
These libraries are essential for data manipulation, analysis and visualization. Some Data Science and Analysis Libraries are:
These libraries help us build and interact with web applications and services. Some Web Development Libraries are:
These libraries help build machine learning models, perform deep learning and work with AI algorithms. Some Machine Learning and AI Libraries are:
A library is a group of modules that collectively address a certain set of requirements or applications. A module is a file (.py file) that includes functions, class defining statements and variables linked to a certain activity. The term "standard library modules" refers to the pre-installed Python modules.
Interesting Facts about Python Modules:
1. import this:There is actually a poem written by Tim Peters named as THE ZEN OF PYTHON which can be read by just writing import this in the interpreter.
Output
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!2. The "antigravity" Easter Egg in Python: The statement import antigravity in Python is a fun Easter egg that was added to the language as a joke. When we run this command, it opens a web browser to a comic from the popular webcomic xkcd (specifically, xkcd #353: "Python").