This question is her to put your problem or question and the RG colleagues will try to find a solution.
Do you have any questions? comments? Suggestions? Please, let me know.
Please put your question clearly. Please write comments if you find anything incorrect.
Creating a Python Object
Nissan = Cars()
Self Variable:
SELF is a default variable that contains the memory address of the current object in Python. Instance variables and methods can be referred to by the self-variable. When the object of a class is created, the memory location of the object is contained by its object name. This memory location is passed to the SELF internally, as SELF knows the memory address of the object, so the variable and method of an object are accessible. The first argument to any object method is SELF because the first argument is always object reference. This process takes place automatically whether you call it or not.
https://www.geeksforgeeks.org/python-object/
Pointers allow you to create great efficiency in parts of your code. They also cause confusion for beginners and can lead to various memory management bugs, even for experts.
https://realpython.com/pointers-in-python/
class ClassName: # list of python class variables # python class constructor # python class method definitions
Example
#definition of the class starts here class Person: #initializing the variables name = "" age = 0 #defining constructor def __init__(self, personName, personAge): self.name = personName self.age = personAge #defining class methods def showName(self): print(self.name) def showAge(self): print(self.age)
https://www.digitalocean.com/community/tutorials/python-classes-objects
https://stackoverflow.com/questions/22921093/query-on-object-class-type-class-in-python
https://medium.com/@ewho.ruth2014/mastering-object-oriented-programming-in-python-advanced-techniques-and-applications-8b10c7161682
http://www.trytoprogram.com/python-programming/python-object-and-class/
As a Python programmer, you must have heard that “Everything in Python is an object.” An integer number is an object. A string is an object. Lists, dictionaries, tuples, pandas data frames, NumPy arrays are objects. Even a function is an object.
In reality, we need to think of python names as a reference to an object. That object may hold references to other objects.
In Python, you’ll have several built-in types at your disposal. Most of them are immutable, and a few are mutable. Single-item data types, such as integers, floats, complex numbers, and Booleans, are always immutable. So, you have no way to change the value of these types. You just have the option of creating a new object with a new value and throwing away the old one.
When it comes to collection or container types, such as strings, lists, tuples, sets, and dictionaries, things are a bit different. Like all other objects, a collection has a unique identity. However, collections internally keep references to all their individual values. This opens the opportunity for mutability.
According to the definition of a mutable object, if you can change the value of that object without changing the object’s identity, then you have a mutable object. In a collection type, you have the collection’s identity and probably several item identities. You can modify the value—and, therefore, the identity—of some of these items while leaving the collection’s identity unchanged. In that case, you have a mutable collection.
Python has both mutable and immutable collection data types. Strings and tuples are immutable, while lists, dictionaries, and sets are mutable. This distinction is crucial for you as a Python developer.
https://realpython.com/python-mutable-vs-immutable-types/
https://qissba.com/object-oriented-programming-in-python/
In Python, you’ll have several built-in types at your disposal. Most of them are immutable, and a few are mutable. Single-item data types, such as integers, floats, complex numbers, and Booleans, are always immutable. So, you have no way to change the value of these types. You just have the option of creating a new object with a new value and throwing away the old one.
https://www.codingeek.com/tutorials/python/mutable-immutable-objects/
https://www.teachoo.com/19908/4177/Data-Types-in-Python/category/Concepts/
https://morioh.com/a/2c9882519f87/mutable-vs-immutable-objects-in-python
This is a very good link for Object Oriented Programming(OOP) in Python:
https://qissba.com/object-oriented-programming-in-python/
In Python, the semicolon ; is indeed used as a statement separator, allowing multiple statements to be written on the same line. It is not commonly used and is generally considered less Pythonic. However, for cases where you need to place multiple statements on one line, it can be used.
Thus, a semicolon in Python denotes separation, rather than termination.
Here's an example of using a semicolon to write two statements on the same line, with the second one being empty:
pythonCopy codex = 10; y = 20; # Three separate statements on the same line, the second one is empty print(x + y) # Output: 30
In this example, we assign the values 10 to x and 20 to y using the semicolon as a statement separator. The second statement is empty, but it's still syntactically correct in Python.
Again, it's worth noting that using semicolons to separate statements is not a common practice in Python, and it's usually recommended to write each statement on a separate line for better readability and maintainability. The Pythonic way is to follow the usual indentation and newline conventions for organizing code.
While Python does not have a specific syntax for multiline comments, developers use triple quotes (either single (”’ ”’) or double (“”” “””)) to create multiline strings, which the interpreter ignores during execution.
In Python, the next() function is used to retrieve the next item from an iterable (like a list, tuple, or set). The iter() function is used to create an iterator from an iterable.
So, next(iter(work_hours)) would retrieve the first item from the work_hours iterable. The purpose of using iter() is to ensure that the iterable is converted into an iterator before using the next() function.
For example, if work_hours is a list of hours worked by employees:
pythonCopy codework_hours = [8, 7, 9, 6, 8] first_employee_hours = next(iter(work_hours)) print(first_employee_hours) # This will print the hours of the first employee (8 in this case)
Keep in mind that if there are no more items left to retrieve from the iterable, using next() will raise a StopIteration exception. To avoid this, you can provide a default value to the next() function like next(iter(work_hours), None), which will return None if the iterable is exhausted.
float('-inf') represents negative infinity in the floating-point number system. Negative infinity is a special value that is used to represent a value that is smaller than any finite real number. You might encounter this value when performing mathematical operations that result in values that are smaller than any representable finite number. It's a way to handle cases where a result goes beyond the limits of the floating-point number range.
Do you share the perspective that Python's use of indentation contributes to encountering numerous errors?
Dear Ebrahim Alnsour,
Python's use of indentation to define blocks of code is a unique feature of the language. While it has benefits, such as enforcing clean and readable code, it can also be a source of frustration for some developers, especially those coming from languages that use explicit delimiters (like braces) to define code blocks.
Indentation-related mistakes can indeed happen in Python, and they might include issues like incorrect or inconsistent indentation, which can lead to syntax errors or unintended program behavior. However, many Python developers appreciate the readability that consistent indentation enforces and find that it becomes intuitive with practice.
The key is to maintain a consistent coding style and to be mindful of the indentation rules. Many code editors and integrated development environments (IDEs) have built-in features that help identify and correct indentation errors, which can mitigate the risks associated with indentation-related mistakes.
Ultimately, whether someone agrees that Python's indentation is prone to mistakes or not might depend on their experience, familiarity with the language, and personal preferences.
Python was created by Guido van Rossum, a Dutch programmer مبرمج هولندي. He started working on the language in the late 1980s, and Python was first released in 1991. He remains widely known as the "Benevolent Dictator For Life" (BDFL) of the Python community, although he stepped down from his role as the lead developer in 2018. The language has since been developed and maintained by a dedicated community of developers and contributors.
sort() method vs sorted() function
The primary difference between the two is that list. sort() will sort the list in-place, mutating its indexes and returning None , whereas sorted() will return a new sorted list leaving the original list unchanged. Another difference is that sorted() accepts any iterable قابل للتكرار while list.
Methods represent the behavior of an Object.
https://www.codingem.com/python-what-is-the-difference-between-a-function-and-a-method/
https://freecontent.manning.com/object-oriented-coding-in-python/
Class Diagrams
https://freecontent.manning.com/object-oriented-coding-in-python/
"Becoming a Pythonista" refers to adopting a deep and comprehensive understanding of the Python programming language, along with its best practices, libraries, frameworks, and ecosystem. Here's a roadmap to help you become a proficient Pythonista:
Remember that becoming proficient takes time and practice. Focus on learning and applying concepts gradually. Python's simplicity and readability make it a great language for beginners and experienced developers alike.
Attributes defined by Users: Attributes are created inside the class definition.
Dear Mohammad Rozmeh,
What is a heap?
Heap memory, also known as the heap, is a region of a computer's memory space used for dynamic memory allocation. It is one of the two primary memory areas in a computer's memory hierarchy, with the other being the stack. Here are some key points about heap memory:
In languages like C and C++, programmers have direct control over heap memory allocation and deallocation. In languages like Python, Java, and C#, memory management is abstracted by the runtime environment, making memory management safer but less explicit. Regardless of the language, understanding how heap memory works is important for efficient and reliable program design.
LEGB rule
As we've seen, names in Python spring into existence when they are first assigned a value, and must be assigned before they are used.
Because names are not declared ahead of time, Python uses the location of the assignment of a name to associate it with (i.e., bind it to) a particular namespace. That is, the place where you assign a name determines the namespace it will live in, and hence its scope of visibility.
Besides packaging code, functions add an extra namespace layer to your programs by default, all names assigned inside a function are associated with that function's namespace, and no other. This means that:
LEGB rule really boils down to three simple rules:
In other words, all names assigned inside a function def statement (or lambda expression) are locals by default; functions can use both names in lexically (i.e., physically) enclosing functions and the global scope, but they must declare globals to change them. Python's name resolution is sometimes called the LEGB rule, after the scope names:
https://flylib.com/books/en/2.725.1.99/1/
https://www.geeksforgeeks.org/namespaces-and-scope-in-python/
Role of Underscore(_) in Python
https://www.datacamp.com/tutorial/role-underscore-python
Prof. Nidhal Kamel Taha El-Omari: In your lectures, I hear that "Python is strongly typed"; could you please clarify that with mor examples?
Dear Mohammad Abudayeh,
Of course, I'd be happy to clarify the concept of strong typing in Python and provide you with more examples!
In programming languages, the terms "strongly typed" and "weakly typed" refer to how strictly the type of a value is enforced during operations.
Therefore, "typing" refers to the rules and constraints that govern how different types of data can be used and manipulated. A language is considered "strongly typed" when it enforces strict rules about type compatibility and does not automatically convert between different types without explicit instructions.
In Python, being strongly typed means that the language enforces strict type checking, and operations that involve incompatible types generally result in errors rather than implicit type conversions. Here are a few examples to illustrate this:
These examples demonstrate Python's strong typing by showing that operations involving incompatible types or requiring explicit type conversion are not automatically performed by the language. Instead, you need to explicitly manage the types to ensure that your code behaves as intended.
In contrast, a "weakly typed" language might automatically perform type conversions, which can lead to unexpected behavior if you're not careful. Python's strong typing contributes to code reliability and helps catch potential errors at an early stage.
Prof. Nidhal Kamel Taha El-Omari: But what is the "strongly dynamically typed"?
Dear Yohanes M. I. Santo,
Python is often described as a "Strongly typed", "Dynamically typed" and not as "Statically typed" programming language. Let's break down what this means:
To mention the above description in another way:
https://prepinsta.com/wp-content/uploads/2020/07/difference-between-Dynamic-and-Static-typing.webp
I'm using an older version of Windows, which is Windows 7. Do you have Anaconda or any other software that works with this version?
Dear Sarah Hamza Ghaith,
You can click on this link to put Anaconda on your computer: https://repo.anaconda.com/archive/Anaconda3-2019.10-Windows-x86_64.exe
Just remember that when you use this link, you'll get the right file you need, which is called "Anaconda3-2019.10-Windows-x86_64.exe." This is a file extension associated with software installers for 64-bit versions of the Windows operating system. If you have any specific questions or need more information about this file type or how to use it, please feel free to ask.
Best regards,
Nidhal
Dear Sarah Hamza Ghaith,
To download JetBrains PyCharm for Windows 7:
Note: Some popular IDEs include NetBeans,Visual Studio, Eclipse, IntelliJ IDEA, and PyCharm, each tailored to specific programming languages and development purposes. Each tailored to specific programming languages and development purposes. For instance, NetBeans is an IDE primarily used for Java application development, although it supports other programming languages as well, including HTML5, PHP, C/C++, and more. It provides a range of features to assist developers in writing, debugging, and deploying software.
What is "TabError: inconsistent use of tabs and spaces in indentation" in python?
Dear Anas Mohammad Esbaitan,
The "TabError: inconsistent use of tabs and spaces in indentation" error in Python occurs when you mix tabs and spaces for indentation within the same block of code. Python relies on consistent indentation using either tabs or spaces, but not both, to determine the structure of your code. Mixing tabs and spaces can lead to ambiguity and errors.
To fix this error, you should ensure that your code uses either tabs or spaces for indentation throughout.
https://colab.research.google.com/
I think that Google Colab (Collaboratoryتعاونية) is the most useful platform for online Python coding and experimentation. Google Colab is indeed a popular choice for many users, especially in the data science and machine learning communities. It offers a free and cloud-based Jupyter Notebook environment with access to powerful hardware accelerators like GPUs and TPUs, which can be very advantageous for computationally intensive tasks.
Python is a versatile programming language that allows you to do some unusual and unexpected things. Here are a few examples of strange or unconventional things you can do in Python:
https://www.youtube.com/watch?app=desktop&v=WM1x2L1dFJk
Programming languages are a matter of personal preference, and everyone has their own preferences and reasons for liking or disliking a particular language. If you have specific concerns or reasons for disliking Python, feel free to share them, and I'd be happy to provide more information or alternative solutions if possible. Remember that there are many programming languages to choose from, and it's essential to use the one that best suits your needs and preferences.
Prof. Nidhal Kamel Taha El-Omari: Could you please explain again Monkey and Duck in python?
Dear Osama Mead,
In Python, "donkey" and "monkey" are not standard terms used to describe specific programming concepts or features. It's possible that these terms are being used informally or colloquially, but they do not have widely recognized meanings in the context of Python programming.
However, there are some terms that are commonly used in Python programming:
Java and Python use different strategies for managing memory and object lifetimes, and each approach has its own advantages and trade-offs.
In Python:
Consider a scenario where object A has a reference to object B, object B references object C, and object C, in turn, references object B. If object A removes its reference to object B, traditional reference counting would not lead to the deletion of objects B and C, as both would still have a reference count of 1.
In CPython (the C implementation of Python), circular references like this are detected and handled through a distinct garbage collection routine that runs periodically. This garbage collection mechanism identifies and resolves circular references, ensuring that objects B and C are eventually freed from memory when they are no longer reachable, even if reference counting alone would not have caught this situation.
In Java:
Benefits of Java's Garbage Collection Approach:
Drawbacks and Considerations:
Whether Java's approach is better than Python's depends on the specific use case:
Ultimately, the choice between Python and Java (or another language with a different memory management strategy) depends on your project's requirements and constraints. Each approach has its strengths and weaknesses, and the best choice will vary based on your application's needs.
One common issue we observe among students learning Python is related to the global variables used inside functions. By default, when attempting to modify a global variable within a function, Python generates a local variable with the same name rather than altering the global variable. To make changes to a global variable, the 'global' keyword must be employed.
Moreover, we've noticed that some Python errors are associated with the use of default arguments of the functions. It's important to note that default arguments in function definitions are evaluated only once when the function is defined, not each time the function is called. This can lead to unexpected behavior when mutable objects such as lists or dictionaries are employed as default arguments.
One common issue we observe among students learning Python pertains to whitespace and indentation. Python is notably sensitive to whitespace, not only for indentation but also for line breaks. Even a minor whitespace or indentation error can result in syntax errors or unexpected program behavior. Another related concern is the mixing of tabs and spaces for indentation, which can cause Python code to malfunction. Therefore, it is advisable to maintain consistent spacing, typically in multiples of four spaces.
I strongly advise all Python students to peruse the following article: "8 Mistakes That Every Python Programmer Should Avoid."
You can access it through the following link:
https://levelup.gitconnected.com/8-mistakes-that-every-python-programmer-should-avoid-7acdf4e61dc7
Read In this article: Python is a simple and easy to learn programming language. Many beginner programmers opt (Optional Practical Training)for python as their first programming language due to its simple syntax, easiness of use and applications.
I suggest that every Python student reads the following article titled "From Novice to Expert: How to Write a Configuration file in Python"
"When we design software, we normally put a lot of effort into writing high-quality code. But that’s not enough. Good software should also take care of its eco-system, like testing, deployment, network, etc. One of the most important aspects is configuration management."
You can access it through the following link:
https://towardsdatascience.com/from-novice-to-expert-how-to-write-a-configuration-file-in-python-273e171a8eb3
Caution: Be careful when using default values in Python functions, especially with lists or dictionaries. If you make changes to them, it can cause unexpected issues. It's better to use "None" as the default and create the list or dictionary inside the function when needed.
Please inspect the subsequent code and then proceed with its execution:
a=256
b=256
print (a is b)
print(id(a))
print (id(b))
x=257
y=257
print (x is y)
print(id(x))
print (id(y))
The above provided Python code demonstrates the behavior of Python's object caching, particularly for small integers. In Python, small integers in the range of -5 to 256 are cached and reused for performance optimization. Here's an explanation of the code and its results:
In summary, the is operator returns True for a is b because 256 is a cached integer, and a and b reference the same object. However, x is y returns False because 257 is outside the cached range, so x and y are different objects in memory.
Do you know why the following yielded different results in Python?
a1 = "ALLAH"
a2 = "ALLAH"
print (a1 is a2)
b1 = "ALLAH Rabi"
b2 = "ALLAH Rabi"
print (b1 is b2)
This is because of the way Python handles string interning.
In Python, small strings (like "ALLAH") are often interned, which means that they are stored in memory only once, and multiple references to the same string will point to the same memory location. When you use the is operator, it checks if two variables reference the same object in memory. Here's the explanation for the above code:
In Python, it's generally recommended to use == to compare string values for equality and is to check if two variables reference the same object. So, for most practical purposes, you should use a1 == a2 and b1 == b2 to compare the values of the strings.
Do you know why the following yielded different results in Python?
a = [1, 2, 3]
b = a
a += [4]
print(b) # Output: [1, 2, 3, 4]
s = 'ALLAH'
t = s
s += ' Rabi'
print(t) # Output: ALLAH