1563522268
How we can create a testimonial slider using jQuery and CSS? Solution: Responsive Testimonial Slider With jQuery and CSS, an Automated Slider which slides automatically.
Basically, The slider shows the testimonial or feedback text submitted by your customers or users. You can see on many services providing websites, there is a section which is what our client says about us. In other words, the testimonial is a kind of review. Some of the reviews are featured by the websites that is testimonial.
Today you will learn to create an** automated testimonial slider** with responsive design. Most websites use testimonials on their home page for better user attraction. When we buy any services or products first we check reviews, that’s why we should use that on our website. If are using any CMS then are so many plugins available to create this feature. But if you have created your websites from scratch & it’s not based on any content management system then this post will helpful for you.
So, Today I am sharing a Responsive Testimonial Slider with jQuery and CSS. This is an automated or autoplay slider for testimonial based on jQuery. I have used a special jquery based** library for creating this** review slider because of that library made especially for this function. You can show one or multiple testimonials to visitors, just by changing the values.
If you are thinking now how this automatic testimonials slider actually is, then see the video** preview** given below.
See this video preview to getting an idea of how this program looks like.
Video Player
Now you can see this visually both versions desktop & mobile or small screen versions. If you like this, then get the source code of its.
Before sharing source code, let’s talk about it. As you know I have used a special library for creating this program, which is ***slick.js ***(get). Slick JS is developed for making slider or carousel. This library is based on jQuery function, that’s why I am putting this post in JavaScript category because of jQuery also a JavaScript library.
JavaScript or jquery has fewer lines of codes, but they are the main part of this slider. Most of the works is created with CSS, like the** layout**,** UI**styling next/previous buttons, etc. I used the font-awesome library to creating the button‘s icon.
There are all the controls in the JS file, I added autoplay: true; you can also disable this by removing or putting false value. After that, you can control how many testimonials want to show on the webpage. For this, there is a command slidesToShow: 2 . After that, there is a command to set how many users review you want to slide on a single slide. That is slidesToScroll: 1 for controlling this. Also, I put a responsive condition.
There are so many things, I can’t explain it in writing. You will understand easily after getting the codes. For creating this program you have to create 3 files. First for HTML, second for** CSS**, & third for JS. Follow the steps to creating this without any error.
index.html
Create an HTML file named ‘index.html‘ and put these codes given here below.
<!DOCTYPE html>
<!--Code By Webdevtrick ( https://webdevtrick.com )-->
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>jQuery Testimonial Slideshow | Webdevtrick.com</title>
<link href="https://fonts.googleapis.com/css?family=Lato|Patua+One&display=swap" rel="stylesheet">
<link rel='stylesheet' href='https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css'>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="testiSlide">
<div>
<figure class="testimonial">
<blockquote>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
<div class="btn"></div>
</blockquote>
<img src="http://pbs.twimg.com/profile_images/829191018331385858/jxsj-ZmD.jpg" alt="Maksim Goffin" />
<div class="peopl">
<h3>Neil Patel</h3>
<p class="indentity">SEO Expert</p>
</div>
</figure>
</div>
<div>
<figure class="testimonial">
<blockquote>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
<div class="btn"></div>
</blockquote>
<img src="https://secure.gravatar.com/avatar/24a495e3a7316e619af62445f1a86886?s=96&d=mm&r=g" alt="Maksim Goffin" />
<div class="peopl">
<h3>Shaan</h3>
<p class="indentity">Web Developer</p>
</div>
</figure>
</div>
<div>
<figure class="testimonial">
<blockquote>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
<div class="btn"></div>
</blockquote>
<img src="https://yt3.ggpht.com/a/AGF-l7_ESQtd3r7nPdFdP_mmyxn65RFy9JlGT0dGyA=s900-mo-c-c0xffffffff-rj-k-no" alt="Maksim Goffin" />
<div class="peopl">
<h3>Brian Dean</h3>
<p class="indentity">SEO / Blogger</p>
</div>
</figure>
</div>
<div>
<figure class="testimonial">
<blockquote>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
<div class="btn"></div>
</blockquote>
<img src="https://design.sva.edu/wp-content/uploads/2018/08/Sagmeister.jpg" alt="Maksim Goffin" />
<div class="peopl">
<h3>Stefan Sagmeister</h3>
<p class="indentity">Graphic Designer</p>
</div>
</figure>
</div>
</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='http://cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js'></script>
<script src="function.js"></script>
</body>
</html>
style.css
Now create a CSS file named ‘style.css‘ and put these codes.
/* Code By Webdevtrick ( https://webdevtrick.com ) */
html {
font-family: 'Lato', sans-serif;
font-size: 16px;
font-weight: 400;
line-height: 1.5;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
background: #fff;
color: #333
}
body {
margin: 0;
background: #ff5057;
height: 100vh;
}
h3 {
font-family: 'Patua One', cursive;
font-weight: 400;
font-size: 1.4em;
line-height: 1.4em;
color: #fff
}
.container {
box-sizing: content-box;
max-width: 1000px;
margin-left: auto;
margin-right: auto;
padding-left: 15px;
padding-right: 15px;
padding-top: 40px;
padding-bottom: 40px;
}
.indentity {
margin: 0!important
}
figure.testimonial {
position: relative;
float: left;
overflow: hidden;
margin: 10px 1%;
padding: 0 20px;
text-align: left;
box-shadow: none !important;
}
figure.testimonial * {
-webkit-box-sizing: border-box;
box-sizing: border-box;
-webkit-transition: all 0.35s cubic-bezier(0.25, 0.5, 0.5, 0.9);
transition: all 0.35s cubic-bezier(0.25, 0.5, 0.5, 0.9);
}
figure.testimonial img {
max-width: 100%;
vertical-align: middle;
height: 90px;
width: 90px;
border-radius: 50%;
margin: 40px 0 0 10px;
}
figure.testimonial blockquote {
background-color: #fff;
display: block;
font-size: 16px;
font-weight: 400;
line-height: 1.5em;
margin: 0;
padding: 25px 50px 30px;
position: relative;
}
figure.testimonial blockquote:before, figure.testimonial blockquote:after {
content: "\201C";
position: absolute;
color: #ff5057;
font-size: 50px;
font-style: normal;
}
figure.testimonial blockquote:before {
top: 25px;
left: 20px;
}
figure.testimonial blockquote:after {
content: "\201D";
right: 20px;
bottom: 0;
}
figure.testimonial .btn {
top: 100%;
width: 0;
height: 0;
border-left: 0 solid transparent;
border-right: 25px solid transparent;
border-top: 25px solid #fff;
margin: 0;
position: absolute;
}
figure.testimonial .peopl {
position: absolute;
bottom: 45px;
padding: 0 10px 0 120px;
margin: 0;
color: #ffffff;
-webkit-transform: translateY(50%);
transform: translateY(50%);
}
figure.testimonial .peopl h3 {
opacity: 0.9;
margin: 0;
}
.slick-slider {
position: relative;
display: block;
box-sizing: border-box;
user-select: none;
-webkit-touch-callout: none;
-khtml-user-select: none;
-ms-touch-action: pan-y;
touch-action: pan-y;
-webkit-tap-highlight-color: transparent;
}
.slick-list {
position: relative;
display: block;
overflow: hidden;
margin: 0;
padding: 0;
}
.slick-list:focus {
outline: none;
}
.slick-list.dragging {
cursor: pointer;
cursor: hand;
}
.slick-slider .slick-track, .slick-slider .slick-list {
transform: translate3d(0, 0, 0);
}
.slick-track {
position: relative;
top: 0;
left: 0;
display: block;
}
.slick-track:before, .slick-track:after {
display: table;
content: '';
}
.slick-track:after {
clear: both;
}
.slick-loading .slick-track {
visibility: hidden;
}
.slick-slide {
display: none;
float: left;
height: 100%;
min-height: 1px;
}
.slick-slide img {
display: block;
}
.slick-slide.slick-loading img {
display: none;
}
.slick-slide.dragging img {
pointer-events: none;
}
.slick-initialized .slick-slide {
display: block;
}
.slick-loading .slick-slide {
visibility: hidden;
}
.slick-vertical .slick-slide {
display: block;
height: auto;
border: 1px solid transparent;
}
.slick-btn.slick-hidden {
display: none;
}
.slick-prev, .slick-next {
font-size: 0;
line-height: 0;
position: absolute;
top: 40%;
display: block;
width: 20px;
height: 20px;
padding: 0;
transform: translate(0, -50%);
cursor: pointer;
color: transparent;
border: none;
outline: none;
background: transparent;
}
.slick-prev:hover, .slick-prev:focus, .slick-next:hover, .slick-next:focus {
color: transparent;
outline: none;
background: transparent;
}
.slick-prev:hover:before, .slick-prev:focus:before, .slick-next:hover:before, .slick-next:focus:before {
opacity: 1;
}
.slick-prev:before, .slick-next:before {
font-family: "FontAwesome";
font-size: 40px;
line-height: 1;
opacity: .75;
color: white;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.slick-prev {
left: -40px;
}
.slick-prev:before {
content: "";
}
.slick-next {
right: -40px;
}
.slick-next:before {
content: "";
}
function.js
The final step, Create a JavaScript file named ‘function.js‘ and put the codes.
/* Code By Webdevtrick ( https://webdevtrick.com ) */
$(document).ready(function () {
$('.testiSlide').slick({
slidesToShow: 2,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 1500,
responsive: [{
breakpoint: 850,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
infinite: true,
}
}]
});
});
That’s It. You have successfully created a Responsive Testimonial Slider With jQuery and CSS, An** Automated Slider or Carousel**. If you have any doubt or question comment down below.
Thanks for reading. If you liked this post, share it with all of your programming buddies!
Further reading
☞ Build Responsive Real World Websites with HTML5 and CSS3
☞ Advanced CSS and Sass: Flexbox, Grid, Animations and More!
☞ Web Design for Beginners: Real World Coding in HTML & CSS
☞ Foundation CSS Framework - Crash Course for Beginners
☞ The CSS Handbook: a handy guide to CSS for developers
☞ 11 Amazing CSS You Shouldn’t Miss
This post was originally published here
#css #css3 #html #web-development #javascript #jquery
1678535220
In this article, you will learn how to create an automatic image slider using HTML CSS, and JavaScript code. Earlier I shared with you many more types of manual and automatic image sliders. Like other designs, I hope you like this design.
Image slider is a common web element that is currently used in many websites. It is mainly used for the slideshow on the website’s homepage. This type of Auto Image Slideshow is also used to organize many images in a gallery. If you want to learn more about javascript, check out my best HTML, CSS, and javascript projects.
There are two types of image sliders, one automatic and the other manual. In the case of the automatic image slider, the image will change automatically at regular intervals. In the case of the manual, you need to change the image using the Next and Previous buttons.
In this case, the image can be changed automatically and manually. This means that it will automatically change the image and you can also change the image using the Next and Previs buttons separately.
The design can only be created with the help of HTML and CSS but in this case, I have used JavaScript programming code.
If you want to know how these automatic image slideshows work then you can watch the live demo below. Below I have given the source code so you can copy them if you want. You can also download the code using the download button at the bottom of the article.
As you can see in the demo above, this is a very simple image slider with automatic and manual image changes.
In this case, I have used a total of five images but you can use many more if you want. The image will change automatically every 5 seconds. There are also two buttons to change the image.
If you know basic HTML CSS and JavaScript then you can easily understand this design. To create this automatic image slider, first, you need to create an HTML and CSS file.
In this case, I did not create a separate JavaScript file, but you can create a separate file if you want.
I have used a little HTML and CSS code below to create the background of this slider. In this case, I have used the slider height 256 px and width 500 px.
I didn’t use any different colors in the background. If you have seen the demo, you will understand that a shadow has been used around this slide for which I have used box-shadow: 0 0 30px rgba(0, 0, 0, 0.3) here.
<div id=”slider”>
</div>
body {
margin: 10%;
}
#slider {
position: relative;
width: 500px;
height: 265px;
overflow: hidden;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
}
I have added images to this Automatic Image Slider using the code below and designed those images. I have used a total of five images you can increase or decrease as you wish.
If you take a closer look at the CSS code below, you will understand that I have used Slider Ul Width 10000%.
You may wonder why I used 10,000% here. Take a good look at the image below to understand why and how this slider works.
<ul id=”slideWrap”>
<li><img src=”img1.jpg” alt=””></li>
<li><img src=”img2.jpg” alt=””></li>
<li><img src=”img3.jpg” alt=””></li>
<li><img src=”img4.jpg” alt=””></li>
<li><img src=”img5.jpg” alt=””></li>
</ul>
In this case, the height of the image is 256 px and the width is 500 px. Of course in this case you will use the same size of each image.
#slider ul {
position: relative;
list-style: none;
height: 100%;
width: 10000%;
padding: 0;
margin: 0;
transition: all 750ms ease;
left: 0;
}
#slider ul li {
position: relative;
height: 100%;
float: left;
}
#slider ul li img{
width: 500px;
height: 265px;
}
Now we will add the Previs and Next buttons to this slider. The HTML and CSS code below helped to add and design these two buttons.
<a id=”prev” href=”#”>≪</a>
<a id=”next” href=”#”>≫</a>
#slider #prev, #slider #next {
width: 50px;
line-height: 50px;
border-radius: 50%;
font-size: 2rem;
text-shadow: 0 0 20px rgba(0, 0, 0, 0.6);
text-align: center;
color: white;
text-decoration: none;
position: absolute;
top: 50%;
transform: translateY(-50%);
transition: all 150ms ease;
}
I have used a little CSS below to place these two buttons in their proper place. I kept the Previs button 10 pixels away from the left.
I kept the next button 10 px away from the right. As a result, these two buttons are located on either side of the slider.
#slider #prev {
left: 10px;
}
#slider #next {
right: 10px;
}
I have used the following CSS code to use a small amount of hover effect in the background of these two buttons.
#slider #prev:hover, #slider #next:hover {
background-color: rgba(0, 0, 0, 0.5);
text-shadow: 0;
}
So far we have only designed it, now we will implement the image change of this slider.
var responsiveSlider = function() {
var slider = document.getElementById(“slider”);
var sliderWidth = slider.offsetWidth;
var slideList = document.getElementById(“slideWrap”);
var count = 1;
var items = slideList.querySelectorAll(“li”).length;
var prev = document.getElementById(“prev”);
var next = document.getElementById(“next”);
window.addEventListener(‘resize’, function() {
sliderWidth = slider.offsetWidth;
});
First of all, we will decide in advance what kind of work will be done by clicking on the Next button. If you are a beginner then first of all look at the code structure below. Then follow the explanation below which will help you understand better.
var nextSlide = function() {
if(count < items) {
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = items) {
slideList.style.left = “0px”;
count = 1;
}
};
As we have seen, in the nextSlide variable, we have stored how the Next button will work.
First, we added value if (count <items) this code will work when the amount of image is more than count.
Using else if (count = items) we have determined what will happen if the previous function does not work. If both the image and the count are equal then there will be no change in the slider.
‘count’ is the number of times you clicked on the button. If you click on that button once, the value of the count is one. If you click three times at once, the value of the account is 3.
We have decided what kind of change will happen if we click on the Next button. Now we will implement the previous button.
Similarly here we have determined what kind of effect will work if you click on the previous button.
var prevSlide = function() {
if(count > 1) {
count = count – 2;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = 1) {
count = items – 1;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
};
Determining what kind of effect will work when clicking the previous and Next buttons in this Automatic Image Slider. Now we will associate those effects with two buttons.
As I said earlier, we have stored how the Next button will work in a constant called ‘next Slider’. Now below we have instructed that if you click on the Next button, that constant will work.
next.addEventListener(“click”, function() {
nextSlide();
});
We’ve saved what works on the previous button in the ‘prevSlide’. Now below we have instructed that if you click on the previous button, that constant will work.
prev.addEventListener(“click”, function() {
prevSlide();
});
Since this is an automatic image slider, in this case, I have arranged for the image to change automatically. Here I have used 5000 i.e. 5 seconds. This means the image will change every 5 seconds. If you want the images to change every 2 seconds, use 2000 instead of 5000 here.
setInterval(function() {
nextSlide()
}, 8000);
};
window.onload = function() {
responsiveSlider();
}
Hope you learned from this tutorial how I created this beautiful automatic image slider using HTML CSS and JavaScript code. If you want to download the required source code, you can use the download button below.
If you have any problem understanding how to make this auto image slider then you can definitely let me know by commenting.
Original article source at: https://foolishdeveloper.com/
1678557120
在本文中,您将学习如何使用 HTML CSS 和 JavaScript 代码创建自动图像滑块。早些时候,我与您分享了更多类型的手动和自动图像滑块。和其他设计一样,我希望你喜欢这个设计。
图像滑块是一种常见的网络元素,目前在许多网站中使用。主要用于网站首页的幻灯片放映。这种类型的自动图像幻灯片还用于组织图库中的许多图像。如果您想了解有关 javascript 的更多信息,请查看我最好的HTML、CSS 和 javascript 项目。
有两种类型的图像滑块,一种是自动的,另一种是手动的。在自动图像滑块的情况下,图像将定期自动更改。对于手册,您需要使用“下一个”和“上一个”按钮更改图像。
在这种情况下,可以自动和手动更改图像。这意味着它会自动更改图像,您也可以 分别使用 Next 和 Previs 按钮更改图像 。
该设计只能在 HTML 和 CSS 的帮助下创建,但在这种情况下,我使用了 JavaScript 编程代码。
如果你想知道这些自动图像幻灯片是如何工作的,那么你可以观看下面的现场演示。下面我给出了源代码,所以你可以根据需要复制它们。您还可以使用文章底部的下载按钮下载代码。
正如您在上面的演示中看到的,这是一个非常简单的图像滑块,具有自动和手动图像更改功能。
在本例中,我总共使用了五张图片,但如果你愿意,你可以使用更多图片。图像将每 5 秒自动更改一次。还有两个按钮可以更改图像。
如果您了解基本的 HTML CSS 和 JavaScript,那么您可以轻松理解此设计。要创建这个自动图像滑块,首先,您需要创建一个 HTML 和 CSS 文件。
在本例中,我没有创建单独的 JavaScript 文件,但如果需要,您可以创建一个单独的文件。
我在下面使用了一些 HTML 和 CSS 代码来创建这个滑块的背景。在本例中,我使用的滑块高度为 256 像素,宽度为 500 像素。
我没有在背景中使用任何不同的颜色。如果你看过演示,你就会明白这张幻灯片周围使用了阴影,我在这里使用了 box-shadow: 0 0 30px rgba(0, 0, 0, 0.3)。
<div id=”slider”>
</div>
body {
margin: 10%;
}
#slider {
position: relative;
width: 500px;
height: 265px;
overflow: hidden;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
}
我使用下面的代码向这个自动图像滑块添加了图像并设计了这些图像。我一共使用了五张图片,你可以随意增减。
如果你仔细看看下面的 CSS 代码,你就会明白我使用了 Slider Ul Width 10000%。
你可能想知道为什么我在这里使用 10,000%。仔细查看下图,了解此滑块工作的原因和方式。
<ul id=”slideWrap”>
<li><img src=”img1.jpg” alt=””></li>
<li><img src=”img2.jpg” alt=””></li>
<li><img src=”img3.jpg” alt=””></li>
<li><img src=”img4.jpg” alt=””></li>
<li><img src=”img5.jpg” alt=””></li>
</ul>
在本例中,图像的高度为 256 像素,宽度为 500 像素。当然,在这种情况下,您将使用相同大小的每个图像。
#slider ul {
position: relative;
list-style: none;
height: 100%;
width: 10000%;
padding: 0;
margin: 0;
transition: all 750ms ease;
left: 0;
}
#slider ul li {
position: relative;
height: 100%;
float: left;
}
#slider ul li img{
width: 500px;
height: 265px;
}
现在我们将 Previs 和 Next 按钮添加到此滑块。下面的 HTML 和 CSS 代码有助于添加和设计这两个按钮。
<a id=”prev” href=”#”>≪</a>
<a id=”next” href=”#”>≫</a>
#slider #prev, #slider #next {
width: 50px;
line-height: 50px;
border-radius: 50%;
font-size: 2rem;
text-shadow: 0 0 20px rgba(0, 0, 0, 0.6);
text-align: center;
color: white;
text-decoration: none;
position: absolute;
top: 50%;
transform: translateY(-50%);
transition: all 150ms ease;
}
我在下面使用了一些 CSS 将这两个按钮放在适当的位置。我将 Previs 按钮保持在距左侧 10 像素的位置。
我将下一个按钮保持在距离右侧 10 px 的位置。因此,这两个按钮位于滑块的两侧。
#slider #prev {
left: 10px;
}
#slider #next {
right: 10px;
}
我使用下面的 CSS 代码在这两个按钮的背景中使用了少量悬停效果。
#slider #prev:hover, #slider #next:hover {
background-color: rgba(0, 0, 0, 0.5);
text-shadow: 0;
}
到目前为止我们只是设计了它,现在我们来实现这个滑块的图像变化。
var responsiveSlider = function() {
var slider = document.getElementById(“slider”);
var sliderWidth = slider.offsetWidth;
var slideList = document.getElementById(“slideWrap”);
var count = 1;
var items = slideList.querySelectorAll(“li”).length;
var prev = document.getElementById(“prev”);
var next = document.getElementById(“next”);
window.addEventListener(‘resize’, function() {
sliderWidth = slider.offsetWidth;
});
首先,我们将通过单击“下一步”按钮来提前决定要完成什么样的工作。如果您是初学者,那么首先请看下面的代码结构。然后按照下面的说明进行操作,这将帮助您更好地理解。
var nextSlide = function() {
if(count < items) {
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = items) {
slideList.style.left = “0px”;
count = 1;
}
};
正如我们所见,在 nextSlide 变量中,我们存储了 Next 按钮的工作方式。
首先,我们添加了 value if (count <items) 此代码将在图像数量超过 count 时起作用。
使用 else if (count = items) 我们已经确定了如果前面的函数不起作用会发生什么。如果图像和计数都相等,则滑块不会发生变化。
'count' 是您点击按钮的次数。如果您单击该按钮一次,则计数值为一。如果一次单击三次,则该帐户的值为 3。
我们已经决定了如果我们点击 Next 按钮将会发生什么样的变化。现在我们将实现上一个按钮。
类似地,我们已经确定了如果您单击上一个按钮会产生什么样的效果。
var prevSlide = function() {
if(count > 1) {
count = count – 2;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = 1) {
count = items – 1;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
};
确定单击此自动图像滑块中的上一个和下一个按钮时将产生何种效果。现在我们将这些效果与两个按钮相关联。
正如我之前所说,我们已经将 Next 按钮的工作方式存储在名为“next Slider”的常量中。下面我们已经指示如果您单击“下一步”按钮,该常量将起作用。
next.addEventListener(“click”, function() {
nextSlide();
});
我们已经在“prevSlide”中保存了对上一个按钮起作用的内容。下面我们已经说明,如果您单击上一个按钮,该常量将起作用。
prev.addEventListener(“click”, function() {
prevSlide();
});
由于这是一个自动图像滑块,在这种情况下,我已安排图像自动更改。这里我使用了 5000 即 5 秒。这意味着图像将每 5 秒更改一次。如果您希望图像每 2 秒更改一次,请在此处使用 2000 而不是 5000。
setInterval(function() {
nextSlide()
}, 8000);
};
window.onload = function() {
responsiveSlider();
}
希望您从本教程中了解到我是如何使用 HTML CSS 和 JavaScript 代码创建这个漂亮的自动图像滑块的。如果您想下载所需的源代码,可以使用下面的下载按钮。
如果您对如何制作此自动图像滑块有任何疑问,那么您绝对可以通过评论让我知道。
文章原文出处:https: //foolishdeveloper.com/
1678560960
В этой статье вы узнаете, как создать автоматический слайдер изображений с помощью HTML CSS и кода JavaScript. Ранее я поделился с вами еще многими типами ручных и автоматических слайдеров изображений . Как и другие проекты, я надеюсь, вам понравится этот дизайн.
Слайдер изображений — это распространенный веб-элемент, который в настоящее время используется на многих веб-сайтах. Он в основном используется для слайд-шоу на главной странице сайта. Этот тип автоматического слайд-шоу изображений также используется для организации большого количества изображений в галерее. Если вы хотите узнать больше о javascript, ознакомьтесь с моими лучшими проектами HTML, CSS и javascript .
Существует два типа ползунков изображений: автоматический и ручной. В случае автоматического ползунка изображения изображение будет автоматически меняться через равные промежутки времени. В случае с мануалом менять изображение нужно с помощью кнопок Next и Previous.
При этом изображение можно менять автоматически и вручную. Это означает, что он автоматически изменит изображение, и вы также можете изменить изображение, используя кнопки «Далее» и «Предварительный просмотр» по отдельности.
Дизайн можно создать только с помощью HTML и CSS, но в данном случае я использовал программный код JavaScript.
Если вы хотите узнать, как работают эти автоматические слайд-шоу изображений , вы можете посмотреть живую демонстрацию ниже. Ниже я дал исходный код, так что вы можете скопировать их, если хотите. Вы также можете скачать код с помощью кнопки загрузки внизу статьи.
Как вы можете видеть в демо выше, это очень простой слайдер изображений с автоматической и ручной сменой изображений.
В этом случае я использовал в общей сложности пять изображений, но вы можете использовать гораздо больше, если хотите. Изображение будет меняться автоматически каждые 5 секунд. Также есть две кнопки для смены изображения.
Если вы знаете основы HTML, CSS и JavaScript, вы легко разберетесь в этом дизайне. Чтобы создать этот автоматический слайдер изображений, сначала вам нужно создать файл HTML и CSS.
В данном случае я не создавал отдельный файл JavaScript, но вы можете создать отдельный файл, если хотите.
Я использовал небольшой код HTML и CSS ниже, чтобы создать фон для этого слайдера. В этом случае я использовал ползунок высотой 256 пикселей и шириной 500 пикселей.
Я не использовал разные цвета фона. Если вы видели демонстрацию, вы поймете, что вокруг этого слайда была использована тень, для которой я использовал box-shadow: 0 0 30px rgba(0, 0, 0, 0.3) здесь.
<div id=”slider”>
</div>
body {
margin: 10%;
}
#slider {
position: relative;
width: 500px;
height: 265px;
overflow: hidden;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);
}
Я добавил изображения в этот автоматический слайдер изображений, используя приведенный ниже код, и разработал эти изображения. Я использовал в общей сложности пять изображений, которые вы можете увеличивать или уменьшать по своему усмотрению.
Если вы внимательно посмотрите на приведенный ниже код CSS, вы поймете, что я использовал Slider Ul Width 10000%.
Вы можете задаться вопросом, почему я использовал здесь 10 000%. Внимательно посмотрите на изображение ниже, чтобы понять, почему и как работает этот ползунок.
<ul id=”slideWrap”>
<li><img src=”img1.jpg” alt=””></li>
<li><img src=”img2.jpg” alt=””></li>
<li><img src=”img3.jpg” alt=””></li>
<li><img src=”img4.jpg” alt=””></li>
<li><img src=”img5.jpg” alt=””></li>
</ul>
В этом случае высота изображения составляет 256 пикселей, а ширина — 500 пикселей. Конечно, в этом случае вы будете использовать одинаковый размер каждого изображения.
#slider ul {
position: relative;
list-style: none;
height: 100%;
width: 10000%;
padding: 0;
margin: 0;
transition: all 750ms ease;
left: 0;
}
#slider ul li {
position: relative;
height: 100%;
float: left;
}
#slider ul li img{
width: 500px;
height: 265px;
}
Теперь мы добавим к этому слайдеру кнопки Previs и Next. Приведенный ниже код HTML и CSS помог добавить и спроектировать эти две кнопки.
<a id=”prev” href=”#”>≪</a>
<a id=”next” href=”#”>≫</a>
#slider #prev, #slider #next {
width: 50px;
line-height: 50px;
border-radius: 50%;
font-size: 2rem;
text-shadow: 0 0 20px rgba(0, 0, 0, 0.6);
text-align: center;
color: white;
text-decoration: none;
position: absolute;
top: 50%;
transform: translateY(-50%);
transition: all 150ms ease;
}
Я использовал небольшой CSS ниже, чтобы разместить эти две кнопки на своих местах. Я оставил кнопку «Предварительный просмотр» на расстоянии 10 пикселей от левого края.
Я оставил следующую кнопку на расстоянии 10 пикселей от правого края. В результате эти две кнопки расположены по обе стороны от ползунка.
#slider #prev {
left: 10px;
}
#slider #next {
right: 10px;
}
Я использовал следующий код CSS, чтобы использовать небольшой эффект наведения на фоне этих двух кнопок.
#slider #prev:hover, #slider #next:hover {
background-color: rgba(0, 0, 0, 0.5);
text-shadow: 0;
}
Пока мы его только оформили, теперь реализуем смену изображения этого слайдера.
var responsiveSlider = function() {
var slider = document.getElementById(“slider”);
var sliderWidth = slider.offsetWidth;
var slideList = document.getElementById(“slideWrap”);
var count = 1;
var items = slideList.querySelectorAll(“li”).length;
var prev = document.getElementById(“prev”);
var next = document.getElementById(“next”);
window.addEventListener(‘resize’, function() {
sliderWidth = slider.offsetWidth;
});
Прежде всего, мы заранее определимся, какая работа будет выполнена, нажав на кнопку «Далее». Если вы новичок, то прежде всего посмотрите на структуру кода ниже. Затем следуйте приведенным ниже объяснениям, которые помогут вам лучше понять.
var nextSlide = function() {
if(count < items) {
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = items) {
slideList.style.left = “0px”;
count = 1;
}
};
Как мы видели, в переменной nextSlide мы сохранили, как будет работать кнопка «Далее».
Во-первых, мы добавили значение if (count <items), этот код будет работать, когда количество изображений больше, чем count.
С помощью else if (count = items) мы определили, что произойдет, если предыдущая функция не сработает. Если и изображение, и количество одинаковы, то слайдер не изменится.
'count' - это количество раз, когда вы нажали на кнопку. Если вы нажмете на эту кнопку один раз, значение счетчика будет равно единице. Если вы нажмете три раза одновременно, значение учетной записи равно 3.
Мы решили, какие изменения произойдут, если мы нажмем кнопку «Далее». Теперь мы реализуем предыдущую кнопку.
Точно так же здесь мы определили, какой эффект будет работать, если вы нажмете на предыдущую кнопку.
var prevSlide = function() {
if(count > 1) {
count = count – 2;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
else if(count = 1) {
count = items – 1;
slideList.style.left = “-” + count * sliderWidth + “px”;
count++;
}
};
Определение того, какой эффект будет работать при нажатии кнопок «Назад» и «Далее» в этом автоматическом слайдере изображений. Теперь мы свяжем эти эффекты с двумя кнопками.
Как я уже говорил ранее, мы сохранили то, как кнопка «Далее» будет работать, в константе под названием «следующий слайдер». Теперь ниже мы указали, что если вы нажмете кнопку «Далее», эта константа будет работать.
next.addEventListener(“click”, function() {
nextSlide();
});
Мы сохранили то, что работает на предыдущей кнопке, в «prevSlide». Теперь ниже мы указали, что если вы нажмете на предыдущую кнопку, эта константа будет работать.
prev.addEventListener(“click”, function() {
prevSlide();
});
Поскольку это автоматический слайдер изображений , в данном случае я устроил автоматическое изменение изображения. Здесь я использовал 5000 т.е. 5 секунд. Это означает, что изображение будет меняться каждые 5 секунд. Если вы хотите, чтобы изображения менялись каждые 2 секунды, используйте здесь 2000 вместо 5000.
setInterval(function() {
nextSlide()
}, 8000);
};
window.onload = function() {
responsiveSlider();
}
Надеюсь, вы узнали из этого урока, как я создал этот красивый автоматический слайдер изображений , используя код HTML CSS и JavaScript. Если вы хотите загрузить необходимый исходный код, вы можете использовать кнопку загрузки ниже.
Если у вас есть какие-либо проблемы с пониманием того, как сделать этот автоматический слайдер изображений, вы обязательно можете сообщить мне об этом в комментариях.
Original article source at: https://foolishdeveloper.com/
1655630160
Install via pip:
$ pip install pytumblr
Install from source:
$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install
A pytumblr.TumblrRestClient
is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:
client = pytumblr.TumblrRestClient(
'<consumer_key>',
'<consumer_secret>',
'<oauth_token>',
'<oauth_secret>',
)
client.info() # Grabs the current user information
Two easy ways to get your credentials to are:
interactive_console.py
tool (if you already have a consumer key & secret)client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user
client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog
client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post
client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog
Creating posts
PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.
The default supported types are described below.
We'll show examples throughout of these default examples while showcasing all the specific post types.
Creating a photo post
Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload
#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")
#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
tweet="Woah this is an incredible sweet post [URL]",
data="/Users/johnb/path/to/my/image.jpg")
#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
caption="## Mega sweet kittens")
Creating a text post
Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html
#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")
Creating a quote post
Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported
#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")
Creating a link post
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
description="Search is pretty cool when a duck does it.")
Creating a chat post
Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)
#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])
Creating an audio post
Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr
#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")
#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")
Creating a video post
Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload
#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
embed="http://www.youtube.com/watch?v=40pUYLacrj4")
#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")
Editing a post
Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.
client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")
Reblogging a Post
Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.
client.reblog(blogName, id=125356, reblog_key="reblog_key")
Deleting a post
Deleting just requires that you own the post and have the post id
client.delete_post(blogName, 123456) # Deletes your post :(
A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):
client.create_text(blogName, tags=['hello', 'world'], ...)
Getting notes for a post
In order to get the notes for a post, you need to have the post id and the blog that it is on.
data = client.notes(blogName, id='123456')
The results include a timestamp you can use to make future calls.
data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])
# get posts with a given tag
client.tagged(tag, **params)
This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).
You'll need pyyaml
installed to run it, but then it's just:
$ python interactive-console.py
and away you go! Tokens are stored in ~/.tumblr
and are also shared by other Tumblr API clients like the Ruby client.
The tests (and coverage reports) are run with nose, like this:
python setup.py test
Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license
1669003576
In this Python article, let's learn about Mutable and Immutable in Python.
Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.
Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.
Objects of built-in type that are mutable are:
Objects of built-in type that are immutable are:
Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.
In Python, everything is treated as an object. Every object has these three attributes:
While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.
Check out this free python certificate course to get started with Python.
I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:
#Creating a list which contains name of Indian cities
cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]
# Printing the elements from the list cities, separated by a comma & space
for city in cities:
print(city, end=’, ’)
Output [1]: Delhi, Mumbai, Kolkata
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(cities)))
Output [2]: 0x1691d7de8c8
#Adding a new city to the list cities
cities.append(‘Chennai’)
#Printing the elements from the list cities, separated by a comma & space
for city in cities:
print(city, end=’, ’)
Output [3]: Delhi, Mumbai, Kolkata, Chennai
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(cities)))
Output [4]: 0x1691d7de8c8
The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.
Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.
Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0.
#Creating a Tuple with variable name ‘foo’
foo = (1, 2)
#Changing the index[0] value from 1 to 3
foo[0] = 3
TypeError: 'tuple' object does not support item assignment
Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:
#Creating a Tuple which contains English name of weekdays
weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’
# Printing the elements of tuple weekdays
print(weekdays)
Output [1]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(weekdays)))
Output [2]: 0x1691cc35090
#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’
weekdays += ‘Pythonday’,
#Printing the elements of tuple weekdays
print(weekdays)
Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(weekdays)))
Output [4]: 0x1691cc8ad68
This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it. Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.
Also Read: Understanding the Exploratory Data Analysis (EDA) in Python
Where can you use mutable and immutable objects:
Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.
Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.
Watch outs: Non transitive nature of Immutability:
OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–
#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements
#The elements (lists) contains the name, age & gender
person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])
#printing the tuple
print(person)
Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(person)))
Output [2]: 0x1691ef47f88
#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4
person[0][1] = 4
#printing the updated tuple
print(person)
Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(person)))
Output [4]: 0x1691ef47f88
In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.
Also Read: Real-Time Object Detection Using TensorFlow
Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–
#creating a list (mutable object) which contains tuples(immutable) as it’s elements
list1 = [(1, 2, 3), (4, 5, 6)]
#printing the list
print(list1)
Output [1]: [(1, 2, 3), (4, 5, 6)]
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(list1)))
Output [2]: 0x1691d5b13c8
#changing object reference at index 0
list1[0] = (7, 8, 9)
#printing the list
Output [3]: [(7, 8, 9), (4, 5, 6)]
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(list1)))
Output [4]: 0x1691d5b13c8
As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.
Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’
x = 10
#printing the value of ‘x’
print(x)
Output [1]: 10
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(x)))
Output [2]: 0x538fb560
#creating an object of integer type with value 10 and reference variable name ‘y’
y = 10
#printing the value of ‘y’
print(y)
Output [3]: 10
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(y)))
Output [4]: 0x538fb560
As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.
Quick check – Python Data Structures
Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.
Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.
Consider a tuple ‘tup’.
Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;
We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.
Mutable Object | Immutable Object |
State of the object can be modified after it is created. | State of the object can’t be modified once it is created. |
They are not thread safe. | They are thread safe |
Mutable classes are not final. | It is important to make the class final before creating an immutable object. |
list, dictionary, set, user-defined classes.
int, float, decimal, bool, string, tuple, range.
Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)
Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.
A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.
A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.
Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.
Join Great Learning Academy’s free online courses and upgrade your skills today.
Original article source at: https://www.mygreatlearning.com