1683553906
I'll be covering all you need to know about CSS variables. A complete guide To CSS Variables with examples. In this tutorial, we will explore what CSS variables are and how to use variables in CSS for creating beautiful responsive websites.
In today's tutorial, I'll be covering all you need to know about CSS variables in 15 minutes. These include it's basic usage, combining it with the calc() function, fallback values and inheritence + psuedo classes.
Variables are the basic building block of any software application. They reduce the redundant tasks for the developers in a program and hold values that have to be used in the entire program. Websites are a bit different. A novice in web programming may not be aware that variables exist at the front-end of web development as well as in CSS. Variables serve the same purpose as they serve when implementation is done using C++, Python, etc. Their work and complexities motivated us to come up with a dedicated blog on CSS variables.
CSS variables (also known as Custom Properties) is a modern CSS specification that is gaining prominence due to widespread browser support. It reduces coding and maintenance time and lets you develop cross browser compatible websites. It also helps in declaring values for reuse across a CSS file, which was previously possible only with preprocessors such as Sass and LESS.
In this blog, we will explore what CSS variables are and how to use variables in CSS for creating beautiful responsive websites. Finally, we will back it up with practical examples. So let’s begin!
CSS variables are custom properties in which you can store a value and use it anywhere in the HTML code. They were introduced in Chrome 49 and have been extremely popular ever since. However, unlike programming languages that support simple initialization and substitution syntax, CSS variables need to be specifically defined whether they are being initialized or substituted. Hence, both of these things have their separate syntaxes.
The initialization of the CSS variable is done by prefixing “–” to the variable name. For example, the following syntax initializes the variable “my_font” to 20px.
--my_font: 20px;
The “my_font” variable can now be used anywhere inside the code with a value of “20px”. Next comes the substitution part. The substitution of a property to the variable can be done only by the “var()” CSS property. Inside the “var(),” we spell the variable name as shown below:
selector {
font-size : var(--my_font);
}
In the above syntax, the font size of the selector will become 20px due to the my_font variable. The “var()” takes another argument apart from the variable name – the fallback value. The fallback value works as a safety net in the variable substitution. In scenarios where the variable value is found to be inaccessible, the fallback value will be used in its place. The fallback value can be declared as shown below:
font-size: var(--my_font, 20px);
Fallback values work differently in different aspects. We will discuss this later in this post with some interesting illustrations related to web browsers.
Before understanding how to use variables in CSS and their importance in the website styling sheet, we need to understand what we used to do before variables in CSS. Before we had this awesome custom property to use, the web developers would use the SASS variables, which had similar intentions but were not smooth and flexible.
SASS variables work similarly to the backend languages where we copy-paste the variable name whenever substitution is required. The initialization, however, is done by prefixing the “$” to the variable name.
$my_font: 20px;
The substitution can be done as shown below:
font-size: $my_font;
The problem with SASS is that it is a preprocessor and not a custom property as a CSS variable. Therefore, any variable declared in SASS needs to be compiled before it can be executed. This makes the variable static and irresistible to change at runtime. A very common problem, therefore, arises when the developer tries to reinitialize the variable as follows.
$my_font: 20px;
selector1 {
font-size: $my_font;
}
selector2 {
$my_font : $my_font + 1;
font-size: $my_font;
}
This will now change the value of my_font to 21px. To reset the value back to 20px, we have to subtract one from it. This does not happen in CSS variables, as we get the advantage of the “calc” function, which we will cover later in this blog.
The following table will help you out to draw a clear picture between the two variables:
SASS Variable | CSS Variable |
Static allocation | Dynamic allocation |
Media queries not supported | Support for media queries |
Requires preprocessor | Preprocessor not required |
An added layer of calculation and complexity | Single-layer and direct variable management |
The SASS variables were commonly used before CSS variables. But the differences between them cannot be ignored. CSS variables are more useful as compared to SASS variables but also differ in many other aspects. Let’s see them in the next section.
Before we go ahead and understand how to use variables in CSS, let’s explore some of the benefits of using variables in CSS. As a web developer, you will be able to relate to it and retrospect on how your life would have been easier with them.
1. Remove Redundancy In Code
Variables remove the redundancy in the code. For example, let’s say we have a very small web page requirement with all the headings (the h tags) of the same “color: red.”
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>CSS Variables</title>
<style>
h2 {
color: red;
}
h3 {
color: red;
}
h4 {
color: red;
}
</style>
</head>
<body>
<center>
<h2>I am heading 2</h2>
<h3>I am heading 3</h3>
<h4>I am heading 4</h4>
</center>
</body>
</html>
Up to this point, everything looks good, and we get the correct output on our webpage.
Now let’s say the team decides to change the color to green for every heading. To do this, we have to go through “find and replace” three times on the page, which is acceptable. But what about constructing a real website where this would be done 100 times or more for just a single change
Variables in CSS eliminate this redundancy from the system where we would just need to change the color once – in the variable’s value.
--heading_color: red;
h2 {
color: var(--heading_color, black);
}
h3 {
color: var(--heading_color, black);
}
h4 {
color: var(--heading_color, black);
}
In the above code, whenever a change arises, I just need to change the variable “heading__color” value from “red” to “green.”
2. No need For Preprocessors
Preprocessors are used for the compilation of variables. Now that we have variables in CSS, we can bid adieu to the processors and perform dynamic activities on the variables. So, in the above example, when I change the color from Red to Green or Cyan (or anything else), I don’t need to compile my page again. Instead, I just press F5, and the changes will be reflected on the web browser.
3. Super Flexible – Declare Anywhere
CSS variables are custom properties of CSS. Similar to other custom properties, you can use the variables in CSS wherever you want. Here is how you can use it with the style tag:
<style>
h2 {
color: var(--heading_color, black);
}
</style>
Using it inline can be another option:
< h2 style = "color: var(--heading_color, black)">I am heading 2</h2 >
4. Improved code readability
For developers, code readability is perhaps one of the most troubling pain points. Consider the following code where we apply color to the various elements on the web page:
h2 {
color: rgb(194, 70, 48);
}
h3 {
color: #c40808;
}
h4 {
color: #8c1c06;
}
Consider a case where 100 lines later, I choose the same h1 color for another paragraph because that was the team plan.
p {
color: rgb(194, 70, 48);
}
But is it predictable that the color used in this paragraph is the same as used in the heading? If color consistency is a point in your website development plan, you might have to look at both the values carefully and verify their similarities. This becomes a lot harder when we talk about maybe 10 or 20 such scenarios. Here is how you can improve the code readability and make it more predictable with variables in CSS:
:root {
--heading_color: red;
--other_color: rgb(194, 70, 48);
}
h2 {
color: var(--heading_color, black);
}
h3 {
color: var(--other_color, black);
}
p {
color: var(--heading_color, black)
}
Since the variable of “p” is similar to “h2”, they both have the same color. An add-on advantage of a readable code is that it becomes a lot easier to find typos. For example, let’s say later on you find out that “H2” and “p” were not supposed to be the same color?
To make them similar, you might have to go through the grilling task of finding and replacing the instances where you have read every value digit by digit. Instead, you can define CSS variables! In the above code, the class “root” defines the variables, which is one of the methods for defining variables in CSS.
CSS Variables and JavaScript
CSS variables can access the DOM of the web page, which is very helpful when dealing with JavaScript. This is a big advantage knowing that JavaScript can help us create awesome code by fetching the variable value and setting it to different values based on predefined conditions.
The end result (i.e., web page) is more dynamic, user-friendly, and gives a lot more control to the developer. The process and code for manipulating the variables with the help of JavaScript are defined in a separate section at the end of this blog.
In the SASS variable section, I mentioned the calc function and how it gives the edge to variables in CSS. The calc function is a vital function for people who love to set things relative to each other. For example, if you are interested in fluid typography in web design, calc function would probably focus on your typography designs.
In addition, the calc function is a basic CSS function that lets us do calculations. For example, Calc functions are generally used to apply relative properties in HTML.
This is how I would make the heading to be 2.5 times larger than the paragraph’s font size.
font-size: calc(20 * 2.5)px;
But the problem here is that even though I have my requirements set properly, I still have to look at my paragraph size. This leads to redundancy in the source code. Variables in CSS can be used with the calc function just like any other property to minimize redundancy.
The approach described above can be replaced with the CSS variables as shown below:
:root {
--paragraph_size: 20px;
}
h2 {
font-size: calc(var(--paragraph_size) * 2.5);
Output:
The second line is the original default font size of the “h2” tag. This code will be further discussed in the exceptions section to point out some of the common mistakes in CSS variables.
In the implementation shown earlier, the root pseudo class (in which the variable is declared) and its significance in the CSS sheet look a bit questionable. However, this class is a part of “scopes,” and this section will highlight its importance in variables in CSS.
The scope property is akin to a variable’s scope in the programming languages. The CSS variable’s scope is no different. This is how you can define a CSS variable under two scopes:
When a variable is defined with a global scope, its existence is defined in the complete document from the time of its declaration. But other programming languages like Python or C++ have an open field between functions where you have the option to define the global scope.
Unfortunately, CSS has no such area due to the lack of a preprocessor. Therefore, in CSS, we use the root pseudo class, which means that the variable is under the document’s root (i.e. global).
:root {
--my_variable: <value>
}
This variable can now be called in any of the selectors in the same document.
:root {
--my_variable: <value>;
}
div {
<property>: var(--my_variable, fallback)
}
The root selector works because variables in CSS can access the DOM of the web app code. The root here represents the root of the DOM tree which passes the data to its branches (i.e., complete document).
The local scope of the variables in CSS is restricted by the boundaries of the selectors inside which it has been defined. For instance, in the below code, I have defined the background colour for a div box with id “first_div”:
div {
width: 300px;
height: 200px;
color: white;
font-weight: bold;
font-size: 30px;
}
#first_div {
--my_bg: #692a3c;
background-color: var(--my_bg, black);
}
<body>
<center>
<div id = "first_div">I am a div</div>
</center>
</body>
Output:
Let’s make another div and set the same background color as done with the above div.
#first_div {
--my_bg: #692a3c;
background-color: var(--my_bg, black);
}
#second_div {
background-color: var(--my_bg, white);
}
<div id = "first_div">I am a div</div>
<br><br>
<div id = "second_div">I am a div too!!</div>
Output:
The fallback value is applied (i.e., black background color) to the second div. This happened because the scope of the variable “my_bg” is only within the #first_div tag. Thus, “my_bg” will not be accessible outside those brackets. Try rendering the same web page with “my_bg” defined in the root section and see how it looks!
Now we know that when a variable is defined in the document’s root, it has a global scope and when defined inside any selector, it has a local scope. But, what if the same variable is declared at both places? Who takes the precedence, local or global CSS variable?
The following implementation demonstrates two different techniques to initialize the same CSS variable and its effect on the web page:
<style>
:root {
--my_bg : #692a3c;
}
div {
width: 300px;
height: 200px;
color: white;
font-weight: bold;
font-size: 30px;
}
#first_div {
--my_bg: #f42a3c;
background-color: var(--my_bg, black);
}
#second_div {
background-color: var(--my_bg, black);
}
Output:
None of the divs here has a black background color. This means none of the variables failed and fallback values were never used. Furthermore, if you read the code, the second div has used the global instance of the variable while the first div chose the local variable. Therefore, we can confirm that the local scope has precedence over the global scope in CSS variables.
As far as inheritance is concerned. CSS is infamous for inheritance, which confuses many web developers when things take values that were never defined within their scope. So, what does inheritance mean in CSS?
Inheritance is the relationship between elements that are nested in each other. For example, the following code shows a parent-child relationship:
<div>Hello, I am a parent
<div> Hello, I am a child</div>
</div>
Similarly, we can define other sibling relationships. But these relationships affect each other’s property (down the line from the top) when the value is either set to “inherit” or cannot be found. The following implementation demonstrates the parent-child relationship where the child does not have the CSS variable setting for its background color:
CSS:
#first_div {
--my_bg: blue;
background-color: var(--my_bg, black);
}
#second_div {
background-color: var(--my_bg, black);
}
#third_div {
--my_bg: green;
background-color: var(--my_bg, black);
}
#fourth_div {
background-color: var(--my_bg, black);
}
HTML:
<div id = "first_div">
<div id = "second_div">
<div id = "third_div"></div>
<div id = "fourth_div"></div>
</div>
</div>
If a variable is not found for the element, it inherits the variable value from its parent! Therefore, the above code will see the following background colors for all the div:
All four values are predictable considering the inheritance logic in the above diagram.
Fallback values are the second argument used in the “var()” function, which denotes the substitution of a CSS variable. Fallback values take their name from the job they do – they are used when you fall back with the original variable values.
There are four possibilities through which a CSS variable goes during the substitution.
If the browser does not support variables in CSS, the CSS line of code with “/var()” is ignored completely as the browser does not understand it. In such cases, the browser takes on the default values, i.e., transparent.
Let’s check the code on Google Chrome 46 that does not support the CSS variables.
<style>
:root {
--my_bg : #9e2e50;
}
div {
width: 300px;
height: 200px;
color: black;
font-weight: bold;
font-size: 30px;
background-color: var(--my_bg, black);
}
</style>
</head>
<body>
<center>
<div>
I am a div box!!
</div>
</center>
</body>
The color I applied to the variable “my_bg” is not rendered on the div box. At the same time, the div box does exist here but only transparently.
To demonstrate my web app, I have used an online cross browser testing platform LambdaTest. It provides 3000+ browsers and operating systems to test websites and web apps for cross browser compatibility issues.
If the variable is set to a valid value and is being called within its scope, it will be implemented correctly. So, for example, executing the above code on Google 47 and above will show correct results.
The next scenario comes when the variable is never initialized but is substituted in the code somewhere.
<style>
div {
background-color: var(--my_bg, black);
}
</style>
Output:
The div box takes the fallback value in this case. The same thing happens when the variable is initialized but is called outside of its scope.
If the variable is set to an invalid value based on its usages, such as px or deg for color, the background becomes transparent.
<style>
:root {
--my_bg : 20px;
}
div {
background-color: var(--my_bg, black);
}
</style>
Output:/p>
So the variable line is ignored by the browser.
Fallback values do not work every time the variable throws an error. Furthermore, it only works with a few of the scenarios that are described above. So, as a web developer, what can we do to manage the cross browser compatibility issues?
The best method is to lay a safety net in the selector CSS code that can still place the value to the property in cases that the CSS variable fails.
<style>
:root {
--my_bg : #9e2e50;
}
div {
background-color: #9e2e50;
background-color: var(--my_bg, black);
}
</style>
If the variable is not initialized in the above code, the value will be taken from the first “background-color” initialization. However, if it is initialized, the value will be taken from the variable.
Although not necessarily a strict “fallback,” the variables in CSS can also perform fallback values for various exceptions using the cascading CSS variable methods.
background-color: var(variable_name, var(variable_name, fallback));
However, it has multiple layers of calculation and takes time to execute. This approach is therefore never recommended for a web developer.
Once you know how to use variables in CSS, you will see it is flexible and easy to use. However, they do have a few exceptions that one should remember before declaring and substituting the variables.
Cyclic dependencies are explicit with their names. When dependencies are created with each other, the web developer should verify that the cycle is not created among the variables. If a cycle is created, the code execution could result in an infinite loop that can timeout the web page as it would never load completely.
--variable_name_1 : var(variable_name_2, fallback);
--variable_name_2 : var(variable_name_1, fallback);
A similar process will be seen when a variable will depend on itself during the time of initialization.
--variable_1 = var(variable_1, fallback);
Web developers should always take note of cyclic dependencies while initializing the variables.
The CSS variables are case-sensitive. Therefore, the variables my_var and My_var are both different.
The CSS variable name cannot have a value as an existing property in CSS. So, for example, you cannot initialize a variable with the value “font-size.”
One of the most attractive points for developers who love JavaScript is that variables in CSS can be handled and manipulated with the help of JavaScript easily. To use variables in CSS with JavaScript, you can fetch their current value similar to how JS handles other properties.
The following code fetches the CSS variable (used for the font size) and increases its font size to 40px as we press the button.
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>CSS Variables</title>
<style>
:root {
--fontSize: 20px;
}
div {
width: 300px;
height: 200px;
color: white;
font-weight: bold;
font-size: var(--fontSize, 12px);
background-color: #9e2e50;
}
</style>
<script>
function changeFontSize() {
var r = document.querySelector(':root');
var rs = getComputedStyle(r);
r.style.setProperty('--fontSize', '40px');
}
</script>
</head>
<body>
<center>
<div>
I am a div box!!
</div>
<br><br>
<button onclick="changeFontSize()">Change Font Size</button>
</center>
</body>
</html>
Output:
CSS variables enjoy great support from every major browser. If you know how to use variables in CSS, you can ensure that exceptions and fallbacks are correctly working as per the code.
After implementing, you can use LambdaTest to perform browser compatibility testing to make sure it renders correctly on different browser versions and operating systems.
The most buzzed word of the web development world currently is responsiveness. With Google specifying the responsiveness wherever possible and multiple devices flooding the market, responsive web design has become a priority in itself.
Variables in CSS are not visual elements that can be tested with window resize functionality for responsiveness. But they do affect the components that are visual such as div, images, or anything else. Therefore, responsiveness test are important with the CSS media queries whether variables in CSS support them or not.
The following code implements the CSS media queries along with the CSS variables.
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>CSS Variables</title>
<style>
:root {
--my_color: red;
--my_second_color: green;
}
@media only screen and (min-width: 641px) {
#heading {
color: var(--my_color);
}
}
@media only screen and (max-width: 640px){
#heading {
color: var(--my_second_color);
}
}
</style>
</head>
<body>
<center>
<h2 id = "heading">Wait for it!!!!</h2>
</center>
</body>
</html>
Output:
The text is original of red color in the above code until the window size is greater than 640px. Else, the text color becomes green.
Performing a responsiveness test is not an easy job. You need various devices and owning or leasing every device is not a feasible approach. Instead, we need to choose smart solutions when dealing with responsiveness.
As a web developer, variables have always been a part of my styling sheet. I am sure after befriending them today, and you will start using them regularly too. Variables in CSS remove redundancy from the code, and the best thing is that they are just another property in CSS. However, after implementing CSS variables, you must perform a responsiveness test of your web design. You can follow the responsive web design checklist to ease up the entire responsiveness test process.
In this guide, we learned how to use variables in CSS from its implementation to responsiveness test. I hope variables in CSS are something that you enjoy and share with your fellow developers. If you have come across any interesting experiences with variables in CSS, please share them in the comment section below.
For your reference, check this out:
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties
#css #webdevelopment
1670560264
Learn how to use Python arrays. Create arrays in Python using the array module. You'll see how to define them and the different methods commonly used for performing operations on them.
The artcile covers arrays that you create by importing the array module
. We won't cover NumPy arrays here.
Let's get started!
Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.
Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.
Lists are one of the most common data structures in Python, and a core part of the language.
Lists and arrays behave similarly.
Just like arrays, lists are an ordered sequence of elements.
They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.
However, lists and arrays are not the same thing.
Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.
As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.
Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module
in order to be used.
Arrays of the array module
are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.
They are also more compact and take up less memory and space which makes them more size efficient compared to lists.
If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.
In order to create Python arrays, you'll first have to import the array module
which contains all the necassary functions.
There are three ways you can import the array module
:
import array
at the top of the file. This includes the module array
. You would then go on to create an array using array.array()
.import array
#how you would create an array
array.array()
array.array()
all the time, you could use import array as arr
at the top of the file, instead of import array
alone. You would then create an array by typing arr.array()
. The arr
acts as an alias name, with the array constructor then immediately following it.import array as arr
#how you would create an array
arr.array()
from array import *
, with *
importing all the functionalities available. You would then create an array by writing the array()
constructor alone.from array import *
#how you would create an array
array()
Once you've imported the array module
, you can then go on to define a Python array.
The general syntax for creating an array looks like this:
variable_name = array(typecode,[elements])
Let's break it down:
variable_name
would be the name of the array.typecode
specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.elements
that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode)
alone, without any elements.Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:
TYPECODE | C TYPE | PYTHON TYPE | SIZE |
---|---|---|---|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | wchar_t | Unicode character | 2 |
'h' | signed short | int | 2 |
'H' | unsigned short | int | 2 |
'i' | signed int | int | 2 |
'I' | unsigned int | int | 2 |
'l' | signed long | int | 4 |
'L' | unsigned long | int | 4 |
'q' | signed long long | int | 8 |
'Q' | unsigned long long | int | 8 |
'f' | float | float | 4 |
'd' | double | float | 8 |
Tying everything together, here is an example of how you would define an array in Python:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
#output
#array('i', [10, 20, 30])
Let's break it down:
import array as arr
.numbers
array.arr.array()
because of import array as arr
.array()
constructor, we first included i
, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H
for example, would mean that no negative values are allowed.Keep in mind that if you tried to include values that were not of i
typecode, meaning they were not integer values, you would get an error:
import array as arr
numbers = arr.array('i',[10.0,20,30])
print(numbers)
#output
#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
# numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer
In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.
Another way to create an array is the following:
from array import *
#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])
print(numbers)
#output
#array('d', [10.0, 20.0, 30.0])
The example above imported the array module
via from array import *
and created an array numbers
of float data type. This means that it holds only floating point numbers, which is specified with the 'd'
typecode.
To find out the exact number of elements contained in an array, use the built-in len()
method.
It will return the integer number that is equal to the total number of elements in the array you specify.
import array as arr
numbers = arr.array('i',[10,20,30])
print(len(numbers))
#output
# 3
In the example above, the array contained three elements – 10, 20, 30
– so the length of numbers
is 3
.
Each item in an array has a specific address. Individual items are accessed by referencing their index number.
Indexing in Python, and in all programming languages and computing in general, starts at 0
. It is important to remember that counting starts at 0
and not at 1
.
To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.
The general syntax would look something like this:
array_name[index_value_of_item]
Here is how you would access each individual element in an array:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element
#output
#10
#20
#30
Remember that the index value of the last element of an array is always one less than the length of the array. Where n
is the length of the array, n - 1
will be the index value of the last item.
Note that you can also access each individual element using negative indexing.
With negative indexing, the last element would have an index of -1
, the second to last element would have an index of -2
, and so on.
Here is how you would get each item in an array using that method:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
#output
#30
#20
#10
You can find out an element's index number by using the index()
method.
You pass the value of the element being searched as the argument to the method, and the element's index number is returned.
import array as arr
numbers = arr.array('i',[10,20,30])
#search for the index of the value 10
print(numbers.index(10))
#output
#0
If there is more than one element with the same value, the index of the first instance of the value will be returned:
import array as arr
numbers = arr.array('i',[10,20,30,10,20,30])
#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))
#output
#0
You've seen how to access each individual element in an array and print it out on its own.
You've also seen how to print the array, using the print()
method. That method gives the following result:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
#output
#array('i', [10, 20, 30])
What if you want to print each value one by one?
This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.
For this you can use a simple for
loop:
import array as arr
numbers = arr.array('i',[10,20,30])
for number in numbers:
print(number)
#output
#10
#20
#30
You could also use the range()
function, and pass the len()
method as its parameter. This would give the same result as above:
import array as arr
values = arr.array('i',[10,20,30])
#prints each individual value in the array
for value in range(len(values)):
print(values[value])
#output
#10
#20
#30
To access a specific range of values inside the array, use the slicing operator, which is a colon :
.
When using the slicing operator and you only include one value, the counting starts from 0
by default. It gets the first item, and goes up to but not including the index number you specify.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#get the values 10 and 20 only
print(numbers[:2]) #first to second position
#output
#array('i', [10, 20])
When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#get the values 20 and 30 only
print(numbers[1:3]) #second to third position
#output
#rray('i', [20, 30])
Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.
Let's see some of the most commonly used methods which are used for performing operations on arrays.
You can change the value of a specific element by speficying its position and assigning it a new value:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40
print(numbers)
#output
#array('i', [40, 20, 30])
To add one single value at the end of an array, use the append()
method:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integer 40 to the end of numbers
numbers.append(40)
print(numbers)
#output
#array('i', [10, 20, 30, 40])
Be aware that the new item you add needs to be the same data type as the rest of the items in the array.
Look what happens when I try to add a float to an array of integers:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integer 40 to the end of numbers
numbers.append(40.0)
print(numbers)
#output
#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
# numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer
But what if you want to add more than one value to the end an array?
Use the extend()
method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets
numbers.extend([40,50,60])
print(numbers)
#output
#array('i', [10, 20, 30, 40, 50, 60])
And what if you don't want to add an item to the end of an array? Use the insert()
method, to add an item at a specific position.
The insert()
function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integer 40 in the first position
#remember indexing starts at 0
numbers.insert(0,40)
print(numbers)
#output
#array('i', [40, 10, 20, 30])
To remove an element from an array, use the remove()
method and include the value as an argument to the method.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
numbers.remove(10)
print(numbers)
#output
#array('i', [20, 30])
With remove()
, only the first instance of the value you pass as an argument will be removed.
See what happens when there are more than one identical values:
import array as arr
#original array
numbers = arr.array('i',[10,20,30,10,20])
numbers.remove(10)
print(numbers)
#output
#array('i', [20, 30, 10, 20])
Only the first occurence of 10
is removed.
You can also use the pop()
method, and specify the position of the element to be removed:
import array as arr
#original array
numbers = arr.array('i',[10,20,30,10,20])
#remove the first instance of 10
numbers.pop(0)
print(numbers)
#output
#array('i', [20, 30, 10, 20])
And there you have it - you now know the basics of how to create arrays in Python using the array module
. Hopefully you found this guide helpful.
You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.
Thanks for reading and happy coding!
Original article source at https://www.freecodecamp.org
#python
1666753500
Robust Shortest Path Finder for the Julia Language.
This package provides functions to find robust shortest paths. Please see the reference papers below.
Install
julia> Pkg.add("RobustShortestPath")
This will also install LightGraphs.jl, if you don't have it installed in your Julia system already.
To check if works
julia> Pkg.test("RobustShortestPath")
get_robust_path
This function solves the robust shortest path problem proposed by Bertsimas and Sim (2003) and integrates the idea of Lee and Kwon (2014).
get_robust_path_two
This function solves the robust shortest path problem with two multiplicative uncertain cost coefficients proposed by Kwon et al. (2013).
Example
Example network and data from Kwon et al. (2013):
The above network data should be prepared in the column vector form as follows:
data = [
1 4 79 31 66 28;
1 2 59 97 41 93;
2 4 31 21 50 40;
2 3 90 52 95 38;
2 5 9 23 95 59;
2 6 32 57 73 7;
3 9 89 100 38 21;
3 8 66 13 4 72;
3 6 68 95 58 58;
3 7 47 12 56 20;
4 3 14 19 36 84;
4 9 95 65 88 42;
4 8 88 13 62 54;
5 3 44 8 62 53;
5 6 83 66 30 19;
6 7 33 3 7 8;
6 8 37 99 29 46;
7 11 79 54 23 3;
7 12 10 37 35 43;
8 7 95 71 85 56;
8 10 0 95 16 64;
8 12 30 38 16 3;
9 10 5 69 51 71;
9 11 44 60 60 17;
10 13 79 78 16 59;
10 14 91 59 64 61;
11 14 53 38 84 77;
11 15 80 85 78 6;
11 13 56 23 26 85;
12 15 75 80 31 38;
12 14 1 100 18 40;
13 14 48 28 45 33;
14 15 25 71 33 56;
]
start_node = data[:,1] #first column of data
end_node = data[:,2] #second column of data
p = data[:,3] #third
q = data[:,4] #fourth
c = data[:,5] #fifth
d = data[:,6] #sixth
For a single-coefficient case as in Bertsimas and Sim (2003):
using RobustShortestPath
Gamma=3
origin=1
destination=15
robust_path, robust_x, worst_case_cost = get_robust_path(start_node, end_node, c, d, Gamma, origin, destination)
The result will look like:
([1,4,8,12,15],[1,0,0,0,0,0,0,0,0,0 … 0,0,0,0,0,0,1,0,0,0],295)
For a two-coefficient case as in Kwon et al. (2013):
using RobustShortestPath
Gamma_u=2
Gamma_v=3
origin=1
destination=15
robust_path, robust_x, worst_case_cost = get_robust_path_two(start_node, end_node, p, q, c, d, Gamma_u, Gamma_v, origin, destination)
The result should look like:
([1,4,3,7,12,14,15],[1,0,0,0,0,0,0,0,0,1 … 0,0,0,0,0,0,0,1,0,1],25314.0)
See runtest.jl for more information.
get_shortest_path
This package also provides an interface to dijkstra_shortest_paths
of LightGraphs.jl
.
path, x = get_shortest_path(start_node, end_node, link_length, origin, destination)
Contributor
This package is written and maintained by Changhyun Kwon.
Author: Chkwon
Source Code: https://github.com/chkwon/RobustShortestPath.jl
License: View license
1666082925
This tutorialvideo on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in python programming language. Below are the topics covered in this video:
1:15 What is an array?
2:53 Is python list same as an array?
3:48 How to create arrays in python?
7:19 Accessing array elements
9:59 Basic array operations
- 10:33 Finding the length of an array
- 11:44 Adding Elements
- 15:06 Removing elements
- 18:32 Array concatenation
- 20:59 Slicing
- 23:26 Looping
Python Array Tutorial – Define, Index, Methods
In this article, you'll learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.
The artcile covers arrays that you create by importing the array module
. We won't cover NumPy arrays here.
Let's get started!
Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.
Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.
Lists are one of the most common data structures in Python, and a core part of the language.
Lists and arrays behave similarly.
Just like arrays, lists are an ordered sequence of elements.
They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.
However, lists and arrays are not the same thing.
Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.
As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.
Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module
in order to be used.
Arrays of the array module
are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.
They are also more compact and take up less memory and space which makes them more size efficient compared to lists.
If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.
In order to create Python arrays, you'll first have to import the array module
which contains all the necassary functions.
There are three ways you can import the array module
:
import array
at the top of the file. This includes the module array
. You would then go on to create an array using array.array()
.import array
#how you would create an array
array.array()
array.array()
all the time, you could use import array as arr
at the top of the file, instead of import array
alone. You would then create an array by typing arr.array()
. The arr
acts as an alias name, with the array constructor then immediately following it.import array as arr
#how you would create an array
arr.array()
from array import *
, with *
importing all the functionalities available. You would then create an array by writing the array()
constructor alone.from array import *
#how you would create an array
array()
Once you've imported the array module
, you can then go on to define a Python array.
The general syntax for creating an array looks like this:
variable_name = array(typecode,[elements])
Let's break it down:
variable_name
would be the name of the array.typecode
specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.elements
that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode)
alone, without any elements.Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:
TYPECODE | C TYPE | PYTHON TYPE | SIZE |
---|---|---|---|
'b' | signed char | int | 1 |
'B' | unsigned char | int | 1 |
'u' | wchar_t | Unicode character | 2 |
'h' | signed short | int | 2 |
'H' | unsigned short | int | 2 |
'i' | signed int | int | 2 |
'I' | unsigned int | int | 2 |
'l' | signed long | int | 4 |
'L' | unsigned long | int | 4 |
'q' | signed long long | int | 8 |
'Q' | unsigned long long | int | 8 |
'f' | float | float | 4 |
'd' | double | float | 8 |
Tying everything together, here is an example of how you would define an array in Python:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
#output
#array('i', [10, 20, 30])
Let's break it down:
import array as arr
.numbers
array.arr.array()
because of import array as arr
.array()
constructor, we first included i
, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H
for example, would mean that no negative values are allowed.Keep in mind that if you tried to include values that were not of i
typecode, meaning they were not integer values, you would get an error:
import array as arr
numbers = arr.array('i',[10.0,20,30])
print(numbers)
#output
#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
# numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer
In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.
Another way to create an array is the following:
from array import *
#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])
print(numbers)
#output
#array('d', [10.0, 20.0, 30.0])
The example above imported the array module
via from array import *
and created an array numbers
of float data type. This means that it holds only floating point numbers, which is specified with the 'd'
typecode.
To find out the exact number of elements contained in an array, use the built-in len()
method.
It will return the integer number that is equal to the total number of elements in the array you specify.
import array as arr
numbers = arr.array('i',[10,20,30])
print(len(numbers))
#output
# 3
In the example above, the array contained three elements – 10, 20, 30
– so the length of numbers
is 3
.
Each item in an array has a specific address. Individual items are accessed by referencing their index number.
Indexing in Python, and in all programming languages and computing in general, starts at 0
. It is important to remember that counting starts at 0
and not at 1
.
To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.
The general syntax would look something like this:
array_name[index_value_of_item]
Here is how you would access each individual element in an array:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element
#output
#10
#20
#30
Remember that the index value of the last element of an array is always one less than the length of the array. Where n
is the length of the array, n - 1
will be the index value of the last item.
Note that you can also access each individual element using negative indexing.
With negative indexing, the last element would have an index of -1
, the second to last element would have an index of -2
, and so on.
Here is how you would get each item in an array using that method:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
#output
#30
#20
#10
You can find out an element's index number by using the index()
method.
You pass the value of the element being searched as the argument to the method, and the element's index number is returned.
import array as arr
numbers = arr.array('i',[10,20,30])
#search for the index of the value 10
print(numbers.index(10))
#output
#0
If there is more than one element with the same value, the index of the first instance of the value will be returned:
import array as arr
numbers = arr.array('i',[10,20,30,10,20,30])
#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))
#output
#0
You've seen how to access each individual element in an array and print it out on its own.
You've also seen how to print the array, using the print()
method. That method gives the following result:
import array as arr
numbers = arr.array('i',[10,20,30])
print(numbers)
#output
#array('i', [10, 20, 30])
What if you want to print each value one by one?
This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.
For this you can use a simple for
loop:
import array as arr
numbers = arr.array('i',[10,20,30])
for number in numbers:
print(number)
#output
#10
#20
#30
You could also use the range()
function, and pass the len()
method as its parameter. This would give the same result as above:
import array as arr
values = arr.array('i',[10,20,30])
#prints each individual value in the array
for value in range(len(values)):
print(values[value])
#output
#10
#20
#30
To access a specific range of values inside the array, use the slicing operator, which is a colon :
.
When using the slicing operator and you only include one value, the counting starts from 0
by default. It gets the first item, and goes up to but not including the index number you specify.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#get the values 10 and 20 only
print(numbers[:2]) #first to second position
#output
#array('i', [10, 20])
When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#get the values 20 and 30 only
print(numbers[1:3]) #second to third position
#output
#rray('i', [20, 30])
Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.
Let's see some of the most commonly used methods which are used for performing operations on arrays.
You can change the value of a specific element by speficying its position and assigning it a new value:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40
print(numbers)
#output
#array('i', [40, 20, 30])
To add one single value at the end of an array, use the append()
method:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integer 40 to the end of numbers
numbers.append(40)
print(numbers)
#output
#array('i', [10, 20, 30, 40])
Be aware that the new item you add needs to be the same data type as the rest of the items in the array.
Look what happens when I try to add a float to an array of integers:
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integer 40 to the end of numbers
numbers.append(40.0)
print(numbers)
#output
#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
# numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer
But what if you want to add more than one value to the end an array?
Use the extend()
method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets
numbers.extend([40,50,60])
print(numbers)
#output
#array('i', [10, 20, 30, 40, 50, 60])
And what if you don't want to add an item to the end of an array? Use the insert()
method, to add an item at a specific position.
The insert()
function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
#add the integer 40 in the first position
#remember indexing starts at 0
numbers.insert(0,40)
print(numbers)
#output
#array('i', [40, 10, 20, 30])
To remove an element from an array, use the remove()
method and include the value as an argument to the method.
import array as arr
#original array
numbers = arr.array('i',[10,20,30])
numbers.remove(10)
print(numbers)
#output
#array('i', [20, 30])
With remove()
, only the first instance of the value you pass as an argument will be removed.
See what happens when there are more than one identical values:
import array as arr
#original array
numbers = arr.array('i',[10,20,30,10,20])
numbers.remove(10)
print(numbers)
#output
#array('i', [20, 30, 10, 20])
Only the first occurence of 10
is removed.
You can also use the pop()
method, and specify the position of the element to be removed:
import array as arr
#original array
numbers = arr.array('i',[10,20,30,10,20])
#remove the first instance of 10
numbers.pop(0)
print(numbers)
#output
#array('i', [20, 30, 10, 20])
And there you have it - you now know the basics of how to create arrays in Python using the array module
. Hopefully you found this guide helpful.
Thanks for reading and happy coding!
#python #programming
1665474900
Yet another second editor in RStudio.
The Monaco editor is the code editor which powers 'VS Code'. It is particularly well developed for JavaScript. In addition to the built-in features of the Monaco editor, the widget allows to prettify multiple languages, to view the HTML rendering of Markdown code, and to view and resize SVG images.
With the help of htmltools::browsable
, one can open two Monaco editors in the RStudio viewer pane:
The Monaco editor has many options. If you would like some of them to be available in the monaco
package, please fill an issue.
As any HTML widget, the Monaco editor widget can be used in Shiny apps:
This app uses the sass
package to compile some SCSS code to CSS code. It is one of the examples provided in the monaco
package.
monaco
widget but using the Shiny app locks RStudio.Author: stla
Source Code: https://github.com/stla/monaco
License: View license
1639450620
Os arquivos CSS são os componentes principais de um projeto de desenvolvedor front-end. Eles são usados para estilizar e criar páginas da web. CSS é usado internamente em arquivos HTML usando a style
tag e externamente importando-o para o arquivo HTML necessário.
Neste guia, você aprenderá sobre os erros que podem ocorrer ao importar um arquivo CSS para o seu arquivo React.
CSS ajuda a estilizar páginas da web, mas às vezes o código pode não ser importado corretamente ou pode mostrar alguns erros enquanto está sendo executado. Esses erros podem surgir ao salvar, nomear ou importar o arquivo. Existem quatro coisas que podem dar errado:
id
ouclass
Examinaremos cada uma dessas situações.
Dentro da pasta react-app, algumas pastas são salvas por padrão, como node-module, public e source. Ao criar um programa, todos os códigos HTML são salvos na pasta pública eo resto ( script
, style
, etc.) na pasta de origem.
Considere um exemplo: suponha que você queira criar pastas separadas para cada tipo de arquivo: público para arquivos HTML, src para arquivos JavaScript e uma nova pasta CSS_Files para arquivos CSS. Ao executar o código final após importar todos os arquivos necessários para o teste, um erro aparecerá na tela dizendo: Falha ao compilar: Módulo não encontrado . Abaixo está o código para importar o arquivo e o erro correspondente ao código:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
Este erro é gerado porque o compilador só pode importar arquivos da pasta src. Aqui, o arquivo CSS é salvo fora da pasta src, portanto, o compilador não conseguiu importá-lo. Para fazer esse código funcionar, basta salvar o arquivo CSS dentro da pasta src. Mas se você ainda quiser separar os arquivos, basta criar uma nova pasta dentro da pasta src. Abaixo está o código correto para importar o arquivo CSS.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Um caminho reflete o endereço de um arquivo, portanto, um caminho errado pode facilmente produzir um erro sem que você perceba. Considere um exemplo: suponha que você esteja importando um arquivo CSS para o seu programa React. Você executa o código e ocorre um erro informando que você forneceu um caminho errado, mas ao verificar o caminho novamente, você não vê nada de anormal. Abaixo está o código usado para importar o arquivo e o erro correspondente ao código:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
Como você pode ver no código acima, o problema está exatamente onde o caminho começa. Ao declarar um caminho, apenas dois pontos são necessários, enquanto aqui três pontos foram usados, o que está gerando o erro. Abaixo está o código correto para declarar o caminho:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Em um arquivo CSS, todos os estilos ocorrem dentro de id
ou nos class
atributos de um elemento. Os atributos id
e class
fornecem uma identificação única para o elemento realizar certas ações sem interferir com o resto do código.
Considere um exemplo: suponha que você esteja criando uma página da web com vários divs e estilizando apenas três divs com os seguintes ids: primeiro, segundo e terceiro. Mas quando você executa o código, vê apenas um em div
vez de três. Abaixo estão os códigos para estilizar, criar e inserir dados nos divs.
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
No código acima, o estilo de alguns divs está incompleto. Isso aconteceu porque a página da web contém muitos divs que, ao estilizá-los, um deles acabou com um nome errado e outro teve um erro de grafia. O first
nome div está misturado com o menu
nome div e o third
div está escrito incorretamente. Abaixo está o código CSS correto e o resultado:
#first {
….
}
#second {
….
}
#third {
….
}
As linguagens de programação tratam letras maiúsculas e minúsculas de maneira diferente. Considere um exemplo: suponha que você tenha um arquivo CSS para estilizar os elementos. Desta vez você fez tudo corretamente, mas ainda assim, ao executar o código, um erro aparecerá. Abaixo está o código usado para importar o arquivo e o erro correspondente ao código:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
Ao ver o erro, você pode perceber que há um problema com o nome do arquivo. Ao verificar o nome, você descobre que o arquivo foi salvo como style.css
, mas você o está importando com o nome Style.css
. O erro aqui é gerado pelo S maiúsculo no início do nome do arquivo. Abaixo está o código correto para importar o arquivo:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Como desenvolvedor front-end, você precisa entender a importância do arquivo CSS. Erros podem ser cometidos facilmente ao importar, salvar ou nomear o arquivo, o que pode gerar erros durante a compilação do código. Você deve sempre salvar o arquivo dentro da pasta src, já que o compilador automaticamente procura nele por qualquer tipo de importação de arquivo. Você pode consultar React - Estilo e CSS nos documentos do React para obter mais informações.
1639446900
Файлы CSS являются основными компонентами проекта внешнего интерфейса разработчика. Они используются для стилизации и оформления веб-страниц. CSS используется внутри HTML-файлов с помощью style
тега и извне путем его импорта в требуемый HTML-файл.
В этом руководстве вы узнаете об ошибках, которые могут возникнуть при импорте файла CSS в файл React.
CSS помогает стилизовать веб-страницы, но иногда код может не импортироваться должным образом или может показывать несколько ошибок во время выполнения. Эти ошибки могут возникнуть при сохранении, названии или импорте файла. Есть четыре вещи, которые могут пойти не так:
id
илиclass
Мы рассмотрим каждую из этих ситуаций.
Внутри папки response-app по умолчанию сохраняются некоторые папки, такие как node-module, public и source. При создании программы все коды HTML сохраняются в общей папке, а остальные ( script
, style
и т. Д.) В исходной папке.
Рассмотрим пример: предположим, вы хотите создать отдельные папки для каждого типа файлов: public для файлов HTML, src для файлов JavaScript и новую папку CSS_Files для файлов CSS. Когда вы запустите окончательный код после импорта всех необходимых файлов для тестирования, на экране появится сообщение об ошибке: « Не удалось скомпилировать: модуль не найден» . Ниже приведен код для импорта файла и ошибка, соответствующая коду:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
Эта ошибка возникает из-за того, что компилятор может импортировать файлы только из папки src. Здесь файл CSS сохраняется вне папки src, поэтому компилятору не удалось его импортировать. Чтобы этот код заработал, вам просто нужно сохранить файл CSS в папке src. Но если вы все же хотите разделить файлы, просто создайте новую папку внутри папки src. Ниже приведен правильный код для импорта файла CSS.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Путь отражает адрес файла, поэтому неправильный путь может легко вызвать ошибку, даже если вы этого не заметите. Рассмотрим пример: предположим, вы импортируете файл CSS в свою программу React. Вы запускаете код, и возникает ошибка о том, что вы указали неправильный путь, но когда вы снова проверяете свой путь, вы не видите ничего ненормального. Ниже приведен код, использованный для импорта файла, и ошибка, соответствующая коду:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
Как видно из приведенного выше кода, проблема именно там, где начинается путь. При объявлении пути требуются только две точки, тогда как здесь используются три точки, что вызывает ошибку. Ниже приведен правильный код для объявления пути:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
В файле CSS, все моделирование происходит внутри id
или class
атрибуты элемента. id
И class
атрибуты обеспечивают уникальную идентификацию на элемент , чтобы выполнить определенные действия , не мешая остальным кодом.
Рассмотрим пример: предположим, вы создаете веб-страницу с несколькими div и стилизуете только три div со следующими идентификаторами: first, second и third. Но когда вы запускаете код, вы видите только один div
вместо трех. Ниже приведены коды для стилизации, создания и ввода данных в блоки div.
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
В приведенном выше коде стили некоторых div не завершены. Это произошло из-за того, что веб-страница содержит много div, которые при стилизации один из них получил неправильное имя, а другой - орфографическую ошибку. Имя first
div смешано с menu
именем div, и third
div написан неправильно. Ниже приведен правильный код CSS и результат:
#first {
….
}
#second {
….
}
#third {
….
}
В языках программирования прописные и строчные буквы обрабатываются по-разному. Рассмотрим пример. Предположим, у вас есть файл CSS для стилизации элементов. На этот раз вы все сделали правильно, но все равно при запуске кода выскакивает ошибка. Ниже приведен код, использованный для импорта файла, и ошибка, соответствующая коду:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
Увидев ошибку, вы поймете, что проблема связана с именем файла. Когда вы проверяете имя, вы обнаруживаете, что файл сохраняется как style.css
, но вы импортируете его с именем Style.css
. Ошибка здесь возникает из-за заглавной буквы S в начале имени файла. Ниже приведен правильный код для импорта файла:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Как веб-разработчик, вы должны понимать важность файла CSS. Ошибки можно легко сделать при импорте, сохранении или присвоении имени файлу, что может привести к ошибкам во время компиляции кода. Вы всегда должны сохранять файл в папке src, так как компилятор автоматически ищет в нем любые файлы для импорта. Вы можете обратиться к React - Styling и CSS в документации React для получения дополнительной информации.
1639441740
CSSファイルは、フロントエンド開発者プロジェクトのコアコンポーネントです。これらは、Webページのスタイル設定とデザインに使用されます。CSSは、style
タグを使用してHTMLファイル内で内部的に使用され、必要なHTMLファイルにインポートすることによって外部的に使用されます。
このガイドでは、CSSファイルをReactファイルにインポートするときに発生する可能性のあるエラーについて学習します。
CSSはWebページのスタイル設定に役立ちますが、コードが正しくインポートされなかったり、実行中にいくつかのエラーが表示されたりする場合があります。これらのエラーは、ファイルの保存、命名、またはインポート中に発生する可能性があります。うまくいかないことが4つあります。
id
またはclass
これらの各状況について説明します。
react-appフォルダー内には、node-module、public、sourceなどの一部のフォルダーがデフォルトで保存されます。プログラムを作成するときは、すべてのHTMLコードは、パブリックフォルダと残りの(に保存されscript
、style
元のフォルダで、など)。
例を考えてみましょう。ファイルの種類ごとに個別のフォルダーを作成するとします。HTMLファイルの場合はpublic、JavaScriptファイルの場合はsrc 、CSSファイルの場合は新しいフォルダーCSS_Filesです。テストに必要なすべてのファイルをインポートした後で最終的なコードを実行すると、「コンパイルに失敗しました:モジュールが見つかりません」というエラーが画面に表示されます。以下は、ファイルをインポートするためのコードと、コードに対応するエラーです。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
このエラーは、コンパイラがsrcフォルダからのみファイルをインポートできるために発生します。ここでは、CSSファイルがsrcフォルダーの外に保存されているため、コンパイラーはそれをインポートできませんでした。このコードを機能させるには、CSSファイルをsrcフォルダー内に保存する必要があります。ただし、それでもファイルを分離したい場合は、srcフォルダー内に新しいフォルダーを作成するだけです。以下は、CSSファイルをインポートするための正しいコードです。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
パスはファイルのアドレスを反映しているため、パスを間違えると、気付かないうちにエラーが発生しやすくなります。例を考えてみましょう。CSSファイルをReactプログラムにインポートするとします。コードを実行すると、間違ったパスを指定したことを示すエラーが発生しますが、パスを再度確認しても、異常は見られません。以下は、ファイルのインポートに使用されるコードと、コードに対応するエラーです。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
上記のコードでわかるように、問題はパスが始まるところにあります。パスを宣言する際に必要なドットは2つだけですが、ここでは3つのドットが使用されているため、エラーが発生しています。以下は、パスを宣言するための正しいコードです。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
CSSファイルでは、すべてのスタイル設定は要素のid
またはclass
属性内で行われます。id
そしてclass
属性は、コードの残りの部分と干渉することなく、特定のアクションを実行する要素に固有の識別を提供します。
例を考えてみましょう。複数のdivを含むWebページを作成し、1番目、2番目、3番目のIDを持つ3つのdivのみをスタイリングするとします。ただし、コードを実行すると、div
3つではなく1つしか表示されません。以下は、データのスタイル設定、作成、およびdivへの入力のコードです。
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
上記のコードでは、一部のdivのスタイル設定が不完全です。これは、Webページに多くのdivが含まれているために発生しました。これらのdivのスタイルを設定しているときに、1つが間違った名前になり、もう1つがスペルミスを起こしました。first
div要素の名前はと混同されるmenu
のdiv名とthird
divのは間違って綴られています。以下は正しいCSSコードと結果です。
#first {
….
}
#second {
….
}
#third {
….
}
プログラミング言語では、大文字と小文字の扱いが異なります。例を考えてみましょう。要素をスタイリングするためのCSSファイルがあるとします。今回はすべて正しく実行しましたが、それでもコードを実行するとエラーが表示されます。以下は、ファイルのインポートに使用されるコードと、コードに対応するエラーです。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
エラーを確認することで、ファイル名に問題があることがわかります。名前を確認すると、ファイルはとして保存されてstyle.css
いますが、名前を付けてインポートしていますStyle.css
。ここでのエラーは、ファイル名の先頭にある大文字のSによって生成されます。以下は、ファイルをインポートするための正しいコードです。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
フロントエンド開発者は、CSSファイルの重要性を理解する必要があります。ファイルのインポート、保存、または名前付けの際に間違いが発生しやすく、コードのコンパイル中にエラーが発生する可能性があります。コンパイラがあらゆる種類のファイルインポートを自動的に検索するため、常にsrcフォルダ内にファイルを保存する必要があります。詳細については、ReactドキュメントのReact –スタイリングとCSSを参照してください。
1639439580
Les fichiers CSS sont les composants essentiels d'un projet de développeur front-end. Ils sont utilisés pour styliser et concevoir des pages Web. CSS est utilisé en interne dans les fichiers HTML à l'aide de la style
balise et en externe en l'important dans le fichier HTML requis.
Dans ce guide, vous découvrirez les erreurs qui peuvent survenir lors de l'importation d'un fichier CSS dans votre fichier React.
CSS aide à styliser les pages Web, mais parfois le code peut ne pas être importé correctement ou peut afficher quelques erreurs lors de son exécution. Ces erreurs peuvent survenir lors de l'enregistrement, du nommage ou de l'importation du fichier. Il y a quatre choses qui peuvent mal tourner :
id
ouclass
Nous allons passer en revue chacune de ces situations.
Dans le dossier react-app, certains dossiers sont enregistrés par défaut, tels que node-module, public et source. Lors de la création d'un programme, tous les codes HTML sont enregistrés dans le dossier public et le reste ( script
, style
, etc.) dans le dossier source.
Prenons un exemple : supposons que vous souhaitiez créer des dossiers séparés pour chaque type de fichier : public pour les fichiers HTML, src pour les fichiers JavaScript et un nouveau dossier CSS_Files pour les fichiers CSS. Lorsque vous exécutez le code final après avoir importé tous les fichiers requis pour les tests, une erreur s'affichera à l'écran indiquant, Échec de la compilation : Module introuvable . Ci-dessous le code d'import du fichier et l'erreur correspondant au code :
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
Cette erreur est générée car le compilateur ne peut importer des fichiers qu'à partir du dossier src. Ici, le fichier CSS est enregistré en dehors du dossier src, le compilateur n'a donc pas réussi à l'importer. Pour faire fonctionner ce code, il vous suffit de sauvegarder le fichier CSS dans le dossier src. Mais si vous souhaitez toujours séparer les fichiers, créez simplement un nouveau dossier dans le dossier src. Vous trouverez ci-dessous le code correct pour importer le fichier CSS.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Un chemin reflète l'adresse d'un fichier, donc un mauvais chemin peut facilement produire une erreur sans que vous le remarquiez. Prenons un exemple : supposons que vous importez un fichier CSS dans votre programme React. Vous exécutez le code et une erreur se produit indiquant que vous avez fourni un chemin erroné, mais lorsque vous vérifiez à nouveau votre chemin, vous ne voyez rien d'anormal. Ci-dessous le code utilisé pour importer le fichier et l'erreur correspondant au code :
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
Comme vous pouvez le voir dans le code ci-dessus, le problème est là où commence le chemin. Lors de la déclaration d'un chemin, seuls deux points sont nécessaires, alors qu'ici trois points ont été utilisés, ce qui génère l'erreur. Vous trouverez ci-dessous le code correct pour déclarer le chemin :
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Dans un fichier CSS, tous les styles ont lieu à l'intérieur des id
ou des class
attributs d'un élément. Les attributs id
et class
fournissent une identification unique à l'élément pour effectuer certaines actions sans interférer avec le reste du code.
Prenons un exemple : supposons que vous créez une page Web avec plusieurs div et que vous ne stylisez que trois div avec les identifiants suivants : premier, deuxième et troisième. Mais lorsque vous exécutez le code, vous n'en voyez qu'un div
au lieu de trois. Vous trouverez ci-dessous les codes pour le style, la création et la saisie de données dans les divs.
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
Dans le code ci-dessus, le style de certaines divs est incomplet. Cela s'est produit parce que la page Web contient de nombreuses div qui, tout en les stylisant, l'une d'elles s'est retrouvée avec un nom erroné et une autre a eu une faute d'orthographe. Le first
nom div est mélangé avec le menu
nom div et le third
div est mal orthographié. Ci-dessous le code CSS correct et le résultat :
#first {
….
}
#second {
….
}
#third {
….
}
Les langages de programmation traitent les lettres majuscules et minuscules différemment. Prenons un exemple : supposons que vous ayez un fichier CSS pour les éléments de style. Cette fois, vous avez tout fait correctement, mais quand même, lorsque vous exécutez le code, une erreur s'affiche. Ci-dessous le code utilisé pour importer le fichier et l'erreur correspondant au code :
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
En voyant l'erreur, vous pouvez vous rendre compte qu'il y a un problème avec le nom du fichier. Lorsque vous vérifiez le nom, vous constatez que le fichier est enregistré en tant que style.css
, mais vous l'importez avec le nom Style.css
. L'erreur ici est générée par le S majuscule au début du nom de fichier. Vous trouverez ci-dessous le code correct pour importer le fichier :
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
En tant que développeur front-end, vous devez comprendre l'importance du fichier CSS. Des erreurs peuvent être facilement commises lors de l'importation, de l'enregistrement ou du nom du fichier, ce qui peut générer des erreurs lors de la compilation du code. Vous devez toujours enregistrer le fichier dans le dossier src car le compilateur y recherche automatiquement tout type d'importation de fichier. Vous pouvez vous référer à React - Styling et CSS dans la documentation React pour plus d'informations.
1639436280
Tệp CSS là thành phần cốt lõi của dự án nhà phát triển giao diện người dùng. Chúng được sử dụng để tạo kiểu và thiết kế các trang web. CSS được sử dụng nội bộ trong các tệp HTML bằng style
thẻ và bên ngoài bằng cách nhập CSS vào tệp HTML được yêu cầu.
Trong hướng dẫn này, bạn sẽ tìm hiểu về các lỗi có thể xảy ra khi nhập tệp CSS vào tệp React của bạn.
CSS giúp tạo kiểu cho các trang web, nhưng đôi khi mã có thể không được nhập đúng cách hoặc có thể hiển thị một vài lỗi trong khi nó đang được thực thi. Những lỗi này có thể phát sinh khi lưu, đặt tên hoặc nhập tệp. Có bốn điều có thể xảy ra sai lầm:
id
hoặcclass
Chúng tôi sẽ đi qua từng tình huống này.
Bên trong thư mục ứng dụng phản ứng, một số thư mục được lưu theo mặc định, chẳng hạn như mô-đun nút, công khai và nguồn. Khi tạo một chương trình, tất cả các mã HTML được lưu trong thư mục công cộng và phần còn lại ( script
, style
, vv) trong thư mục nguồn.
Hãy xem xét một ví dụ: Giả sử bạn muốn tạo các thư mục riêng biệt cho từng loại tệp: public cho tệp HTML, src cho tệp JavaScript và một thư mục mới CSS_Files cho tệp CSS. Khi bạn chạy mã cuối cùng sau khi nhập tất cả các tệp được yêu cầu để kiểm tra, một lỗi sẽ hiển thị trên màn hình với nội dung Không biên dịch được: Không tìm thấy mô-đun . Dưới đây là mã để nhập tệp và lỗi tương ứng với mã:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
Lỗi này được tạo ra do trình biên dịch chỉ có thể nhập tệp từ thư mục src. Ở đây, tệp CSS được lưu bên ngoài thư mục src, vì vậy trình biên dịch không nhập được. Để làm cho mã này hoạt động, bạn chỉ cần lưu tệp CSS bên trong thư mục src. Nhưng nếu bạn vẫn muốn tách các tệp, chỉ cần tạo một thư mục mới bên trong thư mục src. Dưới đây là mã chính xác để nhập tệp CSS.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Một đường dẫn phản ánh địa chỉ của một tệp, do đó, một đường dẫn sai có thể dễ dàng tạo ra lỗi mà bạn không nhận ra. Hãy xem xét một ví dụ: Giả sử bạn đang nhập một tệp CSS vào chương trình React của mình. Bạn chạy mã và một lỗi xảy ra cho biết rằng bạn đã cung cấp một đường dẫn sai, nhưng khi bạn kiểm tra lại đường dẫn của mình, bạn không thấy bất kỳ điều gì bất thường. Dưới đây là mã được sử dụng để nhập tệp và lỗi tương ứng với mã:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
Như bạn có thể thấy trong đoạn mã trên, vấn đề nằm ở vị trí bắt đầu của đường dẫn. Trong khi khai báo một đường dẫn chỉ cần hai dấu chấm, trong khi ở đây ba dấu chấm đã được sử dụng, điều này tạo ra lỗi. Dưới đây là mã chính xác để khai báo đường dẫn:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Trong một tệp CSS, tất cả các kiểu diễn ra bên trong id
hoặc các class
thuộc tính của một phần tử. Các id
và class
các thuộc tính cung cấp một định danh duy nhất đến yếu tố để thực hiện hành động nào đó mà không can thiệp với phần còn lại của mã này.
Hãy xem xét một ví dụ: Giả sử bạn đang tạo một trang web có nhiều div và chỉ tạo kiểu cho ba div với các id sau: thứ nhất, thứ hai và thứ ba. Nhưng khi bạn chạy mã, bạn chỉ thấy một div
thay vì ba. Dưới đây là các mã để tạo kiểu, tạo và nhập dữ liệu vào các div.
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
Trong đoạn mã trên, kiểu dáng của một số div không hoàn chỉnh. Điều này xảy ra do trang web chứa nhiều div mà khi tạo kiểu cho chúng, một trong số chúng bị sai tên và một số khác mắc lỗi chính tả. Tên first
div bị trộn lẫn với menu
tên div và third
div bị viết sai chính tả. Dưới đây là mã CSS chính xác và kết quả:
#first {
….
}
#second {
….
}
#third {
….
}
Các ngôn ngữ lập trình xử lý chữ hoa và chữ thường khác nhau. Hãy xem xét một ví dụ: Giả sử bạn có một tệp CSS cho các phần tử tạo kiểu. Lần này bạn đã làm mọi thứ một cách chính xác, nhưng khi bạn chạy mã, một lỗi vẫn xuất hiện. Dưới đây là mã được sử dụng để nhập tệp và lỗi tương ứng với mã:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
Bằng cách nhìn thấy lỗi, bạn có thể nhận ra có vấn đề với tên của tệp. Khi bạn kiểm tra tên, bạn thấy rằng tệp được lưu dưới dạng style.css
, nhưng bạn đang nhập tệp với tên Style.css
. Lỗi ở đây được tạo ra bởi chữ S viết hoa ở đầu tên tệp. Dưới đây là mã chính xác để nhập tệp:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Là một nhà phát triển giao diện người dùng, bạn cần hiểu tầm quan trọng của tệp CSS. Có thể dễ dàng mắc lỗi khi nhập, lưu hoặc đặt tên tệp, điều này có thể tạo ra lỗi trong quá trình biên dịch mã. Bạn phải luôn lưu tệp bên trong thư mục src vì trình biên dịch tự động tìm kiếm thông qua nó cho bất kỳ loại nhập tệp nào. Bạn có thể tham khảo React - Styling và CSS trong tài liệu React để biết thêm thông tin.
1639432560
CSS-Dateien sind die Kernkomponenten eines Frontend-Entwicklerprojekts. Sie werden verwendet, um Webseiten zu gestalten und zu gestalten. CSS wird intern in HTML-Dateien mit dem style
Tag verwendet und extern durch den Import in die erforderliche HTML-Datei.
In dieser Anleitung erfahren Sie, welche Fehler beim Importieren einer CSS-Datei in Ihre React-Datei auftreten können.
CSS hilft beim Gestalten von Webseiten, aber manchmal wird Code möglicherweise nicht richtig importiert oder zeigt einige Fehler an, während er ausgeführt wird. Diese Fehler können beim Speichern, Benennen oder Importieren der Datei auftreten. Es gibt vier Dinge, die schief gehen können:
id
oderclass
Wir werden jede dieser Situationen durchgehen.
Im Ordner "react-app" werden standardmäßig einige Ordner gespeichert, z. B. node-module, public und source. Beim Erstellen eines Programms werden alle HTML-Codes im öffentlichen Ordner und der Rest ( script
, style
, etc.) im Quellordner gespeichert .
Betrachten Sie ein Beispiel: Angenommen, Sie möchten separate Ordner für jede Art von Datei erstellen: public für HTML-Dateien, src für JavaScript-Dateien und einen neuen Ordner CSS_Files für CSS-Dateien. Wenn Sie den endgültigen Code ausführen, nachdem Sie alle erforderlichen Dateien zum Testen importiert haben, wird auf dem Bildschirm ein Fehler angezeigt, der besagt, dass die Kompilierung fehlgeschlagen ist: Modul nicht gefunden . Unten ist der Code zum Importieren der Datei und der dem Code entsprechende Fehler:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
Dieser Fehler wird generiert, weil der Compiler nur Dateien aus dem src-Ordner importieren kann. Hier wird die CSS-Datei außerhalb des src-Ordners gespeichert, sodass der Compiler sie nicht importieren konnte. Damit dieser Code funktioniert, müssen Sie nur die CSS-Datei im Ordner src speichern. Wenn Sie die Dateien dennoch trennen möchten, erstellen Sie einfach einen neuen Ordner im src-Ordner. Unten ist der richtige Code zum Importieren der CSS-Datei.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Ein Pfad spiegelt die Adresse einer Datei wider, sodass ein falscher Pfad leicht zu einem Fehler führen kann, ohne dass Sie es bemerken. Betrachten Sie ein Beispiel: Angenommen, Sie importieren eine CSS-Datei in Ihr React-Programm. Sie führen den Code aus und es wird ein Fehler angezeigt, der besagt, dass Sie einen falschen Pfad angegeben haben, aber wenn Sie Ihren Pfad erneut überprüfen, sehen Sie nichts Ungewöhnliches. Unten ist der Code, der zum Importieren der Datei verwendet wurde, und der dem Code entsprechende Fehler:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
Wie Sie im obigen Code sehen können, liegt das Problem genau dort, wo der Pfad beginnt. Beim Deklarieren eines Pfades sind nur zwei Punkte erforderlich, während hier drei Punkte verwendet wurden, was den Fehler erzeugt. Unten ist der richtige Code zum Deklarieren des Pfads:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
In einer CSS-Datei findet das gesamte Styling innerhalb der id
oder der class
Attribute eines Elements statt. Die Attribute id
und class
bieten eine eindeutige Identifizierung des Elements, um bestimmte Aktionen auszuführen, ohne den Rest des Codes zu beeinträchtigen.
Betrachten Sie ein Beispiel: Angenommen, Sie erstellen eine Webseite mit mehreren Divs und gestalten nur drei Divs mit den folgenden IDs: erste, zweite und dritte. Aber wenn Sie den Code ausführen, sehen Sie nur einen div
statt drei. Unten sind die Codes zum Gestalten, Erstellen und Eingeben von Daten in die Divs.
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
Im obigen Code ist das Styling einiger divs unvollständig. Dies geschah, weil die Webseite viele Divs enthält, von denen beim Styling einer von ihnen einen falschen Namen hatte und ein anderer einen Rechtschreibfehler bekam. Der first
div-Name wird mit dem menu
div-Namen verwechselt und das third
div wird falsch geschrieben. Unten ist der richtige CSS-Code und das Ergebnis:
#first {
….
}
#second {
….
}
#third {
….
}
Programmiersprachen behandeln Groß- und Kleinbuchstaben unterschiedlich. Betrachten Sie ein Beispiel: Angenommen, Sie haben eine CSS-Datei zum Stilen von Elementen. Diesmal haben Sie alles richtig gemacht, aber beim Ausführen des Codes wird trotzdem ein Fehler angezeigt. Unten ist der Code, der zum Importieren der Datei verwendet wurde, und der dem Code entsprechende Fehler:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
Wenn Sie den Fehler sehen, können Sie erkennen, dass ein Problem mit dem Namen der Datei vorliegt. Wenn Sie den Namen überprüfen, stellen Sie fest, dass die Datei als gespeichert style.css
ist, Sie importieren sie jedoch mit dem Namen Style.css
. Der Fehler wird hier durch das große S am Anfang des Dateinamens erzeugt. Unten ist der richtige Code zum Importieren der Datei:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Als Frontend-Entwickler müssen Sie die Bedeutung der CSS-Datei verstehen. Beim Importieren, Speichern oder Benennen der Datei können leicht Fehler gemacht werden, die bei der Codekompilierung zu Fehlern führen können. Sie sollten die Datei immer im src-Ordner speichern, da der Compiler sie automatisch nach Dateiimporten durchsucht. Weitere Informationen finden Sie unter React – Styling und CSS in den React-Dokumenten.
1639410694
Los archivos CSS son los componentes centrales de un proyecto de desarrollador frontend. Se utilizan para diseñar y diseñar páginas web. CSS se usa internamente en archivos HTML usando la style
etiqueta y externamente importándolo en el archivo HTML requerido.
En esta guía, aprenderá sobre los errores que pueden ocurrir al importar un archivo CSS a su archivo React.
CSS ayuda a diseñar páginas web, pero a veces es posible que el código no se importe correctamente o que muestre algunos errores mientras se ejecuta. Estos errores pueden surgir al guardar, nombrar o importar el archivo. Hay cuatro cosas que pueden salir mal:
id
oclass
Analizaremos cada una de estas situaciones.
Dentro de la carpeta react-app, algunas carpetas se guardan de forma predeterminada, como node-module, public y source. Al crear un programa, todos los códigos HTML se guardan en la carpeta pública y el resto ( script
, style
, etc.) en la carpeta de origen.
Considere un ejemplo: suponga que desea crear carpetas separadas para cada tipo de archivo: público para archivos HTML, src para archivos JavaScript y una nueva carpeta CSS_Files para archivos CSS. Cuando ejecute el código final después de importar todos los archivos necesarios para la prueba, aparecerá un error en la pantalla que dice: No se pudo compilar: módulo no encontrado . A continuación se muestra el código para importar el archivo y el error correspondiente al código:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../CSS_Files/style.css';
Este error se genera porque el compilador solo puede importar archivos desde la carpeta src. Aquí, el archivo CSS se guarda fuera de la carpeta src, por lo que el compilador no pudo importarlo. Para que este código funcione, solo tiene que guardar el archivo CSS dentro de la carpeta src. Pero si aún desea separar los archivos, simplemente cree una nueva carpeta dentro de la carpeta src. A continuación se muestra el código correcto para importar el archivo CSS.
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Una ruta refleja la dirección de un archivo, por lo que una ruta incorrecta puede producir fácilmente un error sin que usted se dé cuenta. Considere un ejemplo: suponga que está importando un archivo CSS a su programa React. Ejecuta el código y se produce un error que indica que ha proporcionado una ruta incorrecta, pero cuando vuelve a verificar su ruta, no ve nada anormal. A continuación se muestra el código utilizado para importar el archivo y el error correspondiente al código:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '.../src/CSS_Files/style.css';
Como puede ver en el código anterior, el problema está justo donde comienza la ruta. Mientras se declara una ruta, solo se requieren dos puntos, mientras que aquí se han utilizado tres puntos, lo que está generando el error. A continuación se muestra el código correcto para declarar la ruta:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
En un archivo CSS, todo el estilo se lleva a cabo dentro de id
los class
atributos de un elemento. Los atributos id
y class
proporcionan una identificación única al elemento para realizar determinadas acciones sin interferir con el resto del código.
Considere un ejemplo: suponga que está creando una página web con múltiples divs y diseñando solo tres divs con los siguientes identificadores: primero, segundo y tercero. Pero cuando ejecuta el código, solo ve uno en div
lugar de tres. A continuación se muestran los códigos para diseñar, crear e ingresar datos en los divs.
<body>
<div id="menu"></div>
...
<div id=”first”></div>
<div id=”second”></div>
<div id=”third”></div>
</body>
#menu {
…
}
#second {
…
}
#thrid {
…
}
class Data_1 extends Component {
render() {
return(
<div><p>HELLO!!!</p></div>
)
}
}
ReactDOM.render(<Data_1/>, document.querySelector(‘#first’));
class Data_2 extends Component {
render() {
return(
<div><p>WELCOME TO MY HOME!!!</p></div>
)
}
}
ReactDOM.render(<Data_2/>, document.querySelector(‘#second’));
class Data_3 extends Component {
render() {
return(
<div><p>BYE!!!</p></div>
)
}
}
ReactDOM.render(<Data_3/>, document.querySelector(‘#third’));
En el código anterior, el estilo de algunos divs está incompleto. Esto sucedió porque la página web contiene muchos divs que, al diseñarlos, uno de ellos terminó con un nombre incorrecto y otro tuvo un error de ortografía. El first
nombre div está mezclado con el menu
nombre div y el third
div está escrito incorrectamente. A continuación se muestra el código CSS correcto y el resultado:
#first {
….
}
#second {
….
}
#third {
….
}
Los lenguajes de programación tratan las letras mayúsculas y minúsculas de manera diferente. Considere un ejemplo: suponga que tiene un archivo CSS para diseñar elementos. Esta vez hizo todo correctamente, pero aún así, cuando ejecuta el código, aparece un error. A continuación se muestra el código utilizado para importar el archivo y el error correspondiente al código:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/Style.css';
Al ver el error, puede darse cuenta de que hay un problema con el nombre del archivo. Cuando verifica el nombre, encuentra que el archivo está guardado como style.css
, pero lo está importando con el nombre Style.css
. El error aquí es generado por la S mayúscula al comienzo del nombre del archivo. A continuación se muestra el código correcto para importar el archivo:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import '../src/CSS_Files/style.css';
Como desarrollador de frontend, debe comprender la importancia del archivo CSS. Se pueden cometer errores fácilmente al importar, guardar o nombrar el archivo, lo que puede generar errores durante la compilación del código. Siempre debe guardar el archivo dentro de la carpeta src, ya que el compilador busca automáticamente cualquier tipo de importación de archivos. Puede consultar React - Styling y CSS en los documentos de React para obtener más información.
1575966008
In this Python Interview Questions tutorial, I will introduce you to the most frequently asked questions in Python interviews. Our Python Interview Questions is the one-stop resource from where you can boost your interview preparation. We have 100+ questions on Python Programming basics which will help you with different expertise levels to reap the maximum benefit from our blog.
Q1. What is the difference between list and tuples in Python?
Q2. What are the key features of Python?
Q3. What type of language is python?
Q4. How is Python an interpreted language?
Q5. What is pep 8?
Q6. How is memory managed in Python?
Q7. What is name space in Python?
Q8. What is PYTHON PATH?
Q9. What are python modules?
Q10. What are local variables and global variables in Python?
We have compiled a list of top Python interview questions which are classified into 7 sections, namely:
Ans: Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language. To know more about Scripting, you can refer to the Python Scripting Tutorial.
Ans: An interpreted language is any programming language which is not in machine level code before runtime. Therefore, Python is an interpreted language.
Ans: PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python code for maximum readability.
Ans:
Ans: A namespace is a naming system used to make sure that names are unique to avoid naming conflicts.
Ans: It is an environment variable which is used when a module is imported. Whenever a module is imported, PYTHONPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load.
Ans: Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code.
Some of the commonly used built-in modules are:
Global Variables:
Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program.
Local Variables:
Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space.
Example:
a=2
def add():
b=3
c=a+b
print(c)
add()
Output: 5
When you try to access the local variable outside the function add(), it will throw an error.
Ans: Yes. Python is a case sensitive language.
Ans: Type conversion refers to the conversion of one data type iinto another.
int() – converts any data type into integer type
float() – converts any data type into float type
ord() – converts characters into integer
hex() – converts integers to hexadecimal
oct() – converts integer to octal
tuple() – This function is used to convert to a tuple.
set() – This function returns the type after converting to set.
list() – This function is used to convert any data type to a list type.
dict() – This function is used to convert a tuple of order (key,value) into a dictionary.
str() – Used to convert integer into a string.
complex(real,imag) – This functionconverts real numbers to complex(real,imag) number.
Ans: To install Python on Windows, follow the below steps:
Ans: Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
Ans: Arrays and lists, in Python, have the same way of storing data. But, arrays can hold only a single data type elements whereas lists can hold any data type elements.
Example:
import array as arr
My_Array=arr.array('i',[1,2,3,4])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)
Output:
array(‘i’, [1, 2, 3, 4]) [1, ‘abc’, 1.2]
Ans: A function is a block of code which is executed only when it is called. To define a Python function, the def keyword is used.
Example:
def Newfunc():
print("Hi, Welcome to Morioh")
Newfunc(); #calling the function
Output: Hi, Welcome to Morioh
Ans: init is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the init method.
Here is an example of how to use it.
class Employee:
def __init__(self, name, age,salary):
self.name = name
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
# E1 is the instance of class Employee.
#__init__ allocates memory for E1.
print(E1.name)
print(E1.age)
print(E1.salary)
Output:
XYZ
23
20000
Ans: An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement.
Example:
a = lambda x,y : x+y
print(a(5, 6))
Output: 11
Ans: Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it’s optional. It helps to differentiate between the methods and attributes of a class with local variables.
The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
Ans: [::-1] is used to reverse the order of an array or a sequence.
For example:
import array as arr
My_Array=arr.array('i',[1,2,3,4,5])
My_Array[::-1]
Output: array(‘i’, [5, 4, 3, 2, 1])
[::-1] reprints a reversed copy of ordered data structures such as an array or a list. the original array or list remains unchanged.
Ans: Consider the example shown below:
from random import shuffle
x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High']
shuffle(x)
print(x)
The output of the following code is as below.
[‘Flying’, ‘Keep’, ‘Blue’, ‘High’, ‘The’, ‘Flag’]
Ans: Iterators are objects which can be traversed though or iterated upon.
Ans: Random module is the standard module that is used to generate a random number. The method is defined as:
import random
random.random
The statement random.random() method return the floating point number that is in the range of (0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
Ans: For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.
This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast.
Ans: Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes).
Example:
#Comments in Python start like this
print("Comments in Python start with a #")
Output: Comments in Python start with a #
##3 Q27. What is pickling and unpickling?
Ans: Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
Ans: Functions that return an iterable set of items are called generators.
Ans: In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.
Ans: To convert a string to lowercase, lower() function can be used.
Example:
stg='ABCD'
print(stg.lower())
Output: abcd
Ans: Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.
Ans: Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well.
Example:
"""
Using docstring as a comment.
This code divides 2 numbers
"""
x=8
y=4
z=x/y
print(z)
Output: 2.0
Ans: Operators are special functions. They take one or more values and produce a corresponding result.
is: returns true when 2 operands are true (Example: “a” is ‘a’)
not: returns the inverse of the boolean value
in: checks if some element is present in some sequence
Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
Ans:
Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys.
Let’s take an example:
The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively.
dict={'Country':'India','Capital':'Delhi','PM':'Modi'}
print dict[Country]
India
print dict[Capital]
Delhi
print dict[PM]
Modi
Ans: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it.
Syntax:
The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y
Example:
The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result.
Ans: We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.
Ans: It is used to determine the length of a string, a list, an array, etc.
Example:
stg='ABCD'
len(stg)
Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are:
Ans: The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that.
The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.
The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order.
Ans: Python packages are namespaces containing multiple modules.
Ans: To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function.
Example:
import os
os.remove("xyz.txt")
Ans: Built-in types in Python are as follows –
Ans:
Ans: Elements can be added to an array using the append(), extend() and the insert (i,x) functions.
Example:
a=arr.array('d', [1.1 , 2.1 ,3.1] )
a.append(3.4)
print(a)
a.extend([4.5,6.3,6.8])
print(a)
a.insert(2,3.8)
print(a)
Output:
array(‘d’, [1.1, 2.1, 3.1, 3.4])
array(‘d’, [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8])
array(‘d’, [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])
Ans: Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.
Example:
a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])
print(a.pop())
print(a.pop(3))
a.remove(1.1)
print(a)
Output:
4.6
3.1
array(‘d’, [2.2, 3.8, 3.7, 1.2])
Ans: Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated as procedural as well as structural language.
Ans: Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used.
Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called.
Ans:
Ans: The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.
The steps that are required in this as:
Python libraries are a collection of Python packages. Some of the majorly used python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more.
The split() method is used to separate a given string in Python.
Example:
a="morioh python"
print(a.split())
Output: [‘morioh’, ‘python’]
Modules can be imported using the import keyword. You can import modules in three ways-
Example:
import array #importing using the original module name
import array as arr # importing using an alias name
from array import * #imports everything present in the array module
Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
They are different types of inheritance supported by Python:
Ans: Class in Python is created using the class keyword.
Example:
class Employee:
def __init__(self, name):
self.name = name
E1=Employee("abc")
print(E1.name)
Output: abc
Ans: In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time.
Consider the below example:
# m.py
class MyClass:
def f(self):
print "f()"
We can then run the monkey-patch testing like this:
import m
def monkey_f(self):
print "monkey_f()"
m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()
The output will be as below:
monkey_f()
As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.
Ans: Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java.
Ans: Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
Ans: Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.
Ans: Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes.
Ans: Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers.
Ans: An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN PYTHON THE PASS command does nothing when its executed. it’s a null statement.
For example-
class a:
pass
obj=a()
obj.name="xyz"
print("Name = ",obj.name)
Output:
Name = xyz
Ans: It returns a featureless object that is a base for all classes. Also, it does not take any parameters.
def bs(a): # a = name of list
b=len(a)-1 # minus 1 because we always compare 2 adjacent values
for x in range(b):
for y in range(b-x):
if a[y]>a[y+1]:
a[y],a[y+1]=a[y+1],a[y]
return a
a=[32,5,3,6,7,54,87]
bs(a)
Output: [3, 5, 6, 7, 32, 54, 87]
def pyfunc(r):
for x in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfunc(9)
Output:
*
***
*****
*******
*********
# Enter number of terms needed #0,1,1,2,3,5....
a=int(input("Enter the terms"))
f=0 #first element of series
s=1 #second element of series
if a<=0:
print("The requested series is
",f)
else:
print(f,s,end=" ")
for x in range(2,a):
next=f+s
print(next,end=" ")
f=s
s=next</pre>
Output: Enter the terms 5 0 1 1 2 3
a=int(input("enter number"))
if a>1:
for x in range(2,a):
if(a%x)==0:
print("not prime")
break
else:
print("Prime")
else:
print("not prime")
Output:
enter number 3
Prime
a=input("enter sequence")
b=a[::-1]
if a==b:
print("palindrome")
else:
print("Not a Palindrome")
Output:
enter sequence 323 palindrome
Ans: Let us first write a multiple line solution and then convert it to one-liner code.
with open(SOME_LARGE_FILE) as fh:
count = 0
text = fh.read()
for character in text:
if character.isupper():
count += 1
We will now try to transform this into a single line.
count sum(1 for line in fh for character in line if character.isupper())
Ans: The following code can be used to sort a list in Python:
list = ["1", "4", "0", "6", "9"]
list = [int(i) for i in list]
list.sort()
print (list)
A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
print(A0,A1,A2,A3,A4,A5,A6)
Ans: The following will be the final outputs of A0, A1, … A6
A0 = {‘a’: 1, ‘c’: 3, ‘b’: 2, ‘e’: 5, ‘d’: 4} # the order may vary
A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
Ans: Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of its dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs.
A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
Ans: Django and Flask map the URL’s or addresses typed in the web browsers to functions in Python.
Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work. Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons.
Ans:
Ans: Django MVT Pattern:
The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
Ans: You can use the command edit mysite/setting.py, it is a normal python module with module level representing Django settings.
Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings.
Django uses SQLite as a default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in.
We will add the following lines of code to the setting.py file:
DATABASES = {
'default': {
'ENGINE' : 'django.db.backends.sqlite3',
'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Ans: This is how we can use write a view in Django:
from django.http import HttpResponse
import datetime
def Current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s</body></html> % now
return HttpResponse(html)
Returns the current date and time, as an HTML document
Ans: The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.
Ans: Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side.
So the data itself is not stored client side. This is nice from a security perspective.
Ans: In Django, there are three possible inheritance styles:
Ans: We will use the following code to save an image locally from an URL address
import urllib.request
urllib.request.urlretrieve("URL", "local-filename.jpg")
Ans: Use the following URL format:
http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE
Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time for. For example, to check the Google Webcache age of edureka.co you’d use the following URL:
http://webcache.googleusercontent.com/search?q=cache:edureka.co
Ans: We will use the following lines of code:
from bs4 import BeautifulSoup
import requests
import sys
url = '<a href="http://www.imdb.com/chart/top">http://www.imdb.com/chart/top</a>'
response = requests.get(url)
soup = BeautifulSoup(response.text)
tr = soup.findChildren("tr")
tr = iter(tr)
next(tr)
for movie in tr:
title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0]
year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0]
rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0]
row = title + ' - ' + year + ' ' + ' ' + rating
print(row)
The above code will help scrap data from IMDb’s top 250 list
Ans: map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.
Ans: We use python numpy array instead of a list because of the below three reasons:
For more information on these parameters, you can refer to this section – Numpy Vs List.
Ans: We can get the indices of N maximum values in a NumPy array using the below code:
import numpy as np
arr = np.array([1, 3, 2, 4, 5])
print(arr.argsort()[-3:][::-1])
Output
[ 4 3 1 ]
Ans: We can calculate percentiles with the following code
import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) #Returns 50th percentile, e.g. median
print(p)
Output
3
Ans:
Ans: Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)
Answer: b, c & d.
Dictionaries are created by specifying keys and values.
a) /
b) //
c) %
d) None of the mentioned
Answer: b) //
When both of the operands are integer then python chops out the fraction part and gives you the round off value, to get the accurate answer use floor division. For ex, 5/2 = 2.5 but both of the operands are integer so answer of this expression in python is 2. To get the 2.5 as the answer, use floor division using //. So, 5//2 = 2.5
a) 31 characters
b) 63 characters
c) 79 characters
d) None of the above
Answer: d) None of the above
Identifiers can be of any length.
a) they are used to indicate a private variables of a class
b) they confuse the interpreter
c) they are used to indicate global variables
d) they slow down execution
Answer: a) they are used to indicate a private variable of a class
As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class.
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000
Answer: b) a b c = 1000 2000 3000
Spaces are not allowed in variable names.
try:
if '1' != 1:
raise "someError"
else:
print("someError has not occured")
except "someError":
print ("someError has occured")
a) someError has occured
b) someError has not occured
c) invalid code
d) none of the above
Answer: c) invalid code
A new exception class must inherit from a BaseException. There is no such inheritance here.
a) Error
b) None
c) 25
d) 2
Answer: c) 25
The index -1 corresponds to the last index in the list.
a) outfile = open(“c:scores.txt”, “r”)
b) outfile = open(“c:scores.txt”, “w”)
c) outfile = open(file = “c:scores.txt”, “r”)
d) outfile = open(file = “c:scores.txt”, “o”)
Answer: b) The location contains double slashes ( ) and w is used to indicate that file is being written to.
f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print f.closed
a) True
b) False
c) None
d) Error
Answer: a) True
The WITH statement when used with open file guarantees that the file object is closed when the with block exits.
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs into except block
Answer: c) when no exception occurs
The else part is executed when no exception occurs.
I hope this set of Python Interview Questions will help you in preparing for your interviews. All the best!
Originally published at https://www.edureka.co
#python #interview #interview-questions