<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Francis kinyuru</title>
    <description>The latest articles on DEV Community by Francis kinyuru (@franciskinyuru).</description>
    <link>https://dev.to/franciskinyuru</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F691217%2Fa2cabaa7-9b8a-440f-8367-31686fa2c910.jpg</url>
      <title>DEV Community: Francis kinyuru</title>
      <link>https://dev.to/franciskinyuru</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/franciskinyuru"/>
    <language>en</language>
    <item>
      <title>Rate limiting with bucket4j, redis, Postgres in SpringBoot</title>
      <dc:creator>Francis kinyuru</dc:creator>
      <pubDate>Wed, 26 Jul 2023 09:42:23 +0000</pubDate>
      <link>https://dev.to/franciskinyuru/rate-limiting-with-bucket4j-redis-postgres-in-springboot-4p02</link>
      <guid>https://dev.to/franciskinyuru/rate-limiting-with-bucket4j-redis-postgres-in-springboot-4p02</guid>
      <description>&lt;h2&gt;
  
  
  Redis rate limiting using Bucket4j, redis, postgres in springboot
&lt;/h2&gt;

&lt;h2&gt;
  
  
  Key Objective:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;What specific API will be limited? This could be a single API endpoint, or a group of related endpoints.&lt;/li&gt;
&lt;li&gt;How will the username be used to identify requests? This could be done by including the username in the request header or in the request body, or by using a token-based authentication system.&lt;/li&gt;
&lt;li&gt;What is the custom TPS for each user? This is the maximum number of requests that each user will be allowed to make per second.&lt;/li&gt;
&lt;li&gt;What will happen if a user exceeds their TPS limit? This could result in the request being rejected, or the user being temporarily banned from making requests.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Why Bucket4j
&lt;/h2&gt;

&lt;p&gt;There are many reasons why you might use Bucket4j for rate limiting. Here are a few of the most important ones:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It is a mature and well-tested library. Bucket4j has been around for many years and has been used by a large number of projects. This means that it is a reliable and stable library that you can be confident in using.&lt;/li&gt;
&lt;li&gt;It is easy to use. Bucket4j has a simple and straightforward API that makes it easy to implement rate limiting in your code. You don't need to be an expert in rate limiting to get started with Bucket4j.&lt;/li&gt;
&lt;li&gt;It is flexible. Bucket4j allows you to configure rate limits in a variety of ways. You can specify the number of requests per second, minute, hour, or day. You can also specify burst limits, which allow for a certain number of requests to be made above the regular limit in a short period of time.&lt;/li&gt;
&lt;li&gt;It is efficient. Bucket4j is a very efficient library. It uses a token bucket algorithm to track requests, which is a very efficient way to do rate limiting. This means that Bucket4j will not have a significant impact on the performance of your application.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Overall, Bucket4j is a great choice for rate limiting in Java. It is a mature, well-tested, easy-to-use, flexible, and efficient library.&lt;/p&gt;

&lt;p&gt;Here are some additional benefits of using Bucket4j:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It can protect your API from DDoS attacks. By limiting the number of requests that can be made to your API, you can make it more difficult for attackers to overwhelm your server with requests.&lt;/li&gt;
&lt;li&gt;It can ensure fair resource allocation. By limiting the number of requests that each client can make, you can ensure that all clients have fair access to your API's resources.&lt;/li&gt;
&lt;li&gt;It can improve the performance of your API. By limiting the number of requests that can be made, you can reduce the load on your server, which can improve the performance of your API.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you are looking for a rate limiting library for your Java application, I highly recommend Bucket4j. It is a great choice for protecting your API from DDoS attacks, ensuring fair resource allocation, and improving the performance of your API.&lt;/p&gt;

&lt;p&gt;Lets get now to the actual implementation now on spring boot.&lt;/p&gt;

&lt;p&gt;Below are the dependencies required for the implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-web&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;

        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.projectlombok&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;lombok&amp;lt;/artifactId&amp;gt;
            &amp;lt;optional&amp;gt;true&amp;lt;/optional&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;!-- https://mvnrepository.com/artifact/org.redisson/redisson-spring-boot-starter --&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.redisson&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;redisson-spring-boot-starter&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;3.23.1&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;!-- https://mvnrepository.com/artifact/com.giffing.bucket4j.spring.boot.starter/bucket4j-spring-boot-starter --&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;com.giffing.bucket4j.spring.boot.starter&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;bucket4j-spring-boot-starter&amp;lt;/artifactId&amp;gt;
            &amp;lt;version&amp;gt;0.9.1&amp;lt;/version&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-validation&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.postgresql&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;postgresql&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;runtime&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-data-jpa&amp;lt;/artifactId&amp;gt;
        &amp;lt;/dependency&amp;gt;

        &amp;lt;dependency&amp;gt;
            &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
            &amp;lt;artifactId&amp;gt;spring-boot-starter-test&amp;lt;/artifactId&amp;gt;
            &amp;lt;scope&amp;gt;test&amp;lt;/scope&amp;gt;
        &amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The implementation is maven based and using java 17 for the implementation.&lt;/p&gt;

&lt;p&gt;Configuration under the config package&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;RedisConfig
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.config;

import com.giffing.bucket4j.spring.boot.starter.config.cache.SyncCacheResolver;
import com.giffing.bucket4j.spring.boot.starter.config.cache.jcache.JCacheCacheResolver;
import io.github.bucket4j.distributed.proxy.ProxyManager;
import io.github.bucket4j.grid.jcache.JCacheProxyManager;
import org.redisson.config.Config;
import org.redisson.jcache.configuration.RedissonConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.cache.CacheManager;
import javax.cache.Caching;

@Configuration
public class RedisConfig {

    @Bean
    public Config config(){
        Config config=new Config();
        config.useSingleServer().setAddress("redis://localhost:6379");
        return config;
    }
    @Bean
    public CacheManager cacheManager(Config config){
        CacheManager manager = Caching.getCachingProvider().getCacheManager();
        manager.createCache("cache", RedissonConfiguration.fromConfig(config));
        return manager;
    }
    @Bean
    ProxyManager&amp;lt;String&amp;gt; proxyManager(CacheManager cacheManager){
        return new JCacheProxyManager&amp;lt;&amp;gt;(cacheManager.getCache("cache"));
    }

    @Bean
    @Primary
    public SyncCacheResolver bucket4jCacheResolver(CacheManager cacheManager){
        return new JCacheCacheResolver(cacheManager);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Config bean
&lt;/h2&gt;

&lt;p&gt;This bean creates a configuration object for Redis. This object specifies the address of the Redis server&lt;/p&gt;

&lt;h2&gt;
  
  
  CacheManager bean
&lt;/h2&gt;

&lt;p&gt;This bean creates a cache manager that uses Redis as its backing store. This cache manager will be used to store the rate limits.&lt;/p&gt;

&lt;h2&gt;
  
  
  ProxyManager bean
&lt;/h2&gt;

&lt;p&gt;This bean creates a proxy manager that can be used to access the rate limits in the cache. This proxy manager makes it easy to use the rate limits in your code.&lt;/p&gt;

&lt;h2&gt;
  
  
  SyncCacheResolver Bean
&lt;/h2&gt;

&lt;p&gt;This bean creates a cache resolver that uses the cache manager to resolve the rate limits. This cache resolver is used by Bucket4j to determine the current rate limit for a given request.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;a class="mentioned-user" href="https://dev.to/primary"&gt;@primary&lt;/a&gt; annotation:
&lt;/h2&gt;

&lt;p&gt;This annotation indicates that this is the default cache resolver that should be used by Bucket4j.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;RateLimitConfig
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.config;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.BucketConfiguration;
import io.github.bucket4j.Refill;
import io.github.bucket4j.distributed.proxy.ProxyManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.function.Supplier;

@Configuration
public class RateLimitConfig {
    @Autowired
    public ProxyManager buckets;

    public Bucket resolveBucket(String key,int tps){
        Supplier&amp;lt;BucketConfiguration&amp;gt; configurationSupplier = getConfigSupplier(key,tps);
        return buckets.builder().build(key,configurationSupplier);
    }
    private Supplier&amp;lt;BucketConfiguration&amp;gt; getConfigSupplier(String key, int tps){
        Refill refill=Refill.intervally(tps, Duration.ofSeconds(1));
        Bandwidth limit=Bandwidth.classic(tps,refill);

        return () -&amp;gt; (BucketConfiguration.builder()
                .addLimit(limit)
                .build());
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  resolveBucket() method:
&lt;/h2&gt;

&lt;p&gt;This method takes two parameters: the key of the bucket and the number of requests per second (TPS) that the bucket should allow. The method first calls the getConfigSupplier() method to get a supplier of BucketConfiguration objects. The method then uses the supplier of BucketConfiguration objects to create a Bucket object. The Bucket object is used to rate limit requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  getConfigSupplier() method:
&lt;/h2&gt;

&lt;p&gt;This method creates a BucketConfiguration object that specifies the rate limit for the bucket. The rate limit is specified by the Bandwidth object. The Bandwidth object specifies the number of requests that the bucket can allow per second, and the refill rate. The refill rate specifies how often the bucket is refilled with tokens.&lt;/p&gt;

&lt;p&gt;In my model package&lt;/p&gt;

&lt;h2&gt;
  
  
  model-&amp;gt;request
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.model.request;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Request {
    private String username;
    private String Message;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This represents the sample request body i expect from a post request.&lt;/p&gt;

&lt;h2&gt;
  
  
  model Apiresponse
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.model;

import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ApiResponse {
    private String message;
    private String responseCode;
    private String status;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The expected api response&lt;/p&gt;

&lt;h2&gt;
  
  
  model TpsDb
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.model;

import jakarta.persistence.*;
import lombok.Data;

import java.io.Serializable;
import java.sql.Timestamp;

@Data
@Table(name="tbl_tps")
@Entity
public class TpsDb  implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String username;
    private String path;
    private int tps;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This represents the tables for where the tps details are stored in the DB.&lt;/p&gt;

&lt;h2&gt;
  
  
  Repository
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.repository;

import Rateimiting.model.TpsDb;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface TpsDbRepository extends JpaRepository&amp;lt;TpsDb, Long&amp;gt; {
    TpsDb findByUsernameAndPath(String username, String path);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Added the query tps details my username and path for post request.&lt;/p&gt;

&lt;h2&gt;
  
  
  Service
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.service;

import Rateimiting.config.RateLimitConfig;
import Rateimiting.model.ApiResponse;
import Rateimiting.model.TpsDb;
import Rateimiting.model.request.Request;
import Rateimiting.repository.TpsDbRepository;
import io.github.bucket4j.Bucket;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
public class RateLimitService {
    int tps;
    @Autowired
    private RedissonClient redissonClient;
    private final TpsDbRepository tpsD;

    private final RateLimitConfig rateLimitConfig;
    @Autowired
    public RateLimitService(TpsDbRepository tpsD, RateLimitConfig rateLimitConfig) {
        this.tpsD = tpsD;
        this.rateLimitConfig = rateLimitConfig;
    }

    public ResponseEntity&amp;lt;?&amp;gt; addInfo(Request request, String path) {
        String username = request.getUsername();
        // Check if the TpsDb is cached in Redis
        RMapCache&amp;lt;String, TpsDb&amp;gt; cache = redissonClient.getMapCache("tpsDbCache");
        TpsDb tpsDb = cache.get(username + "-" + path);

        if (tpsDb == null) {
            tpsDb = tpsD.findByUsernameAndPath(path, username);

            if (tpsDb == null) {
                tpsDb = new TpsDb();
                tpsDb.setUsername(username);
                tpsDb.setPath(path);
                tpsDb.setTps(10); // Default TPS value if not found in the database
            }
            cache.put(username + "-" + path, tpsDb);
        }


        int tps = tpsDb.getTps();
        Bucket bucket = rateLimitConfig.resolveBucket(username, tps);
        if (bucket.tryConsume(1)) {
            return ResponseEntity.status(200).body(new ApiResponse("Request Success for user " + username, "4000", "success"));
        } else {
            return ResponseEntity.status(429).body(new ApiResponse("Request failed for user " + username, "4003", "failed"));
        }
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  addInfo() method:
&lt;/h2&gt;

&lt;p&gt;This method takes a request object and a path as input and returns a response indicating whether the request was successful or not. The method first checks if the TpsDb object is cached in Redis. If the TpsDb object is not cached, the method retrieves it from the database. If the TpsDb object is not found in the database, the method creates a new TpsDb object with the default TPS value. The method then creates a Bucket object using the user ID and the TPS value from the TpsDb object. The Bucket object is used to rate limit the request. If the request is successful, the method returns a 200 status code and a success message. Otherwise, the method returns a 429 status code and an error message.&lt;/p&gt;

&lt;p&gt;Finally,&lt;/p&gt;

&lt;h2&gt;
  
  
  Controller.
&lt;/h2&gt;

&lt;p&gt;To create test post request&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package Rateimiting.controller;

import Rateimiting.model.request.Request;
import Rateimiting.service.RateLimitService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

@RestController
@RequestMapping("/v1/")
public class RateLimitController {
    @Autowired
    private HttpServletRequest requests;

    private final RateLimitService rateLimitService;
    @Autowired
    public RateLimitController(RateLimitService rateLimitService) {
        this.rateLimitService = rateLimitService;
    }

    @PostMapping("/rate")
    public ResponseEntity&amp;lt;?&amp;gt; addInfo(@RequestBody Request request){
        String uri = requests.getRequestURI();
        String path = (String) requests.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    return rateLimitService.addInfo(request, path);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  @PostMapping("/rate") annotation:
&lt;/h2&gt;

&lt;p&gt;This annotation marks the addInfo() method as a POST endpoint that can be used to add a new request to the rate limiting system.&lt;/p&gt;

&lt;h2&gt;
  
  
  @RequestBody Request request parameter:
&lt;/h2&gt;

&lt;p&gt;This parameter specifies that the addInfo() method takes a request object as input.&lt;/p&gt;

&lt;h2&gt;
  
  
  String uri = requests.getRequestURI() statement:
&lt;/h2&gt;

&lt;p&gt;This statement gets the URI of the request. The URI is used to get the path of the resource being requested.&lt;/p&gt;

&lt;h2&gt;
  
  
  String path = (String) requests.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE) statement:
&lt;/h2&gt;

&lt;p&gt;This statement gets the path of the resource being requested from the HandlerMapping object.&lt;br&gt;
return rateLimitService.addInfo(request, path); statement: This statement calls the addInfo() method on the RateLimitService class to add the request to the rate limiting system.&lt;/p&gt;

&lt;h2&gt;
  
  
  application.properties
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.sql.init.platform=postgresql
spring.datasource.url=jdbc:postgresql://localhost:5432/dbname
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle=true
spring.jpa.hibernate.ddl-auto=update

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can access the code on my git repo &lt;a href="https://github.com/franciskinyuru/redis-rate-limiting-bucket4j-springboot" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>redis</category>
      <category>springboot</category>
      <category>ratelimiting</category>
      <category>bucket4j</category>
    </item>
    <item>
      <title>USSD 101 with Africastalking</title>
      <dc:creator>Francis kinyuru</dc:creator>
      <pubDate>Sun, 15 May 2022 15:41:27 +0000</pubDate>
      <link>https://dev.to/franciskinyuru/ussd-101-with-africastalking-3846</link>
      <guid>https://dev.to/franciskinyuru/ussd-101-with-africastalking-3846</guid>
      <description>&lt;h2&gt;
  
  
  What is USSD
&lt;/h2&gt;

&lt;p&gt;USSD (Unstructured Supplementary Service Data) is a communications protocol used in GSM networks for sending short text messages. USSD is similar in format to SMS. However, it is an instant messaging service, so messages are not stored on the operator side or on the subscriber's device.&lt;/p&gt;

&lt;h2&gt;
  
  
  Simple Code with Africastalking ENV
&lt;/h2&gt;

&lt;h1&gt;
  
  
  Ussd with Africastalking demo code
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php
#sessionId from the Post request
$sessionId=$_POST['sessionId'];
#serviceCode from the Post request
$serviceCode=$_POST['serviceCode'];
# phoneNumber from the Post request
$phoneNumber=$_POST['phoneNumber'];
# text from the Post request
$text=$_POST['text'];

if ($text == ""){
 # check is the first connection is empty and provice response stating with CON to indicate connection.
 $response="CON What would you want to check \n";
 $response .="1. My Account No \n";
 $response .="2. My phone Number";
}
# if you choose option 1
else if ($text == "1") {
 # business login for the first level response
 $response = "CON Choose account information you want to view \n";
 $response .= "1. Account Number \n";
 $response .= "2. Account Balance";
}
# if you choose option 2
else if ($text == "2") {
 # business login for the first level response with END t end the connection
 $response = "END You phone number is ".$phoneNumber;
# if you choose option 1 the second level supplied option 1
} else if($text == "1*1"){
# business login for the second i.e.*ussd*1*1# level response then END to end the Session
 $accountNumber = "ACC1001";

 $response = "END Your account Number is ".$accountNumber;
}
# if you choose option 1 the second level supplied option 2
else if ($text == "1*2") {
# business login for the second i.e.*ussd*1*1# level response then END to end the Session
 $balance = "KES 10,000";
 # code...
 $response= "END Your balance is ".$balance;
}
# include the Header
header('Content-type: text/plain');
# display the response
echo $response;

?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Deploy the code on heroku my endpoint &lt;a href="https://ussd-uat.herokuapp.com/index.php" rel="noopener noreferrer"&gt;https://ussd-uat.herokuapp.com/index.php&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Go to africastalking create account and then navigate to USSD code and create channel as below.&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fseu77tcj0f22y4t258t2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fseu77tcj0f22y4t258t2.png" alt="Image description" width="800" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You will be provided with the details to simulate the USSD.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Then click Launch Simulator as below&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8w0wfnm3mmdbsu4696h8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8w0wfnm3mmdbsu4696h8.png" alt="Image description" width="363" height="772"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input you test number and click connect as below&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw1oy23mfiju10tnnhix2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fw1oy23mfiju10tnnhix2.png" alt="Image description" width="646" height="772"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Go ahead and test the USSD code&lt;/strong&gt; &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1mdog2xkukqybyhasmrt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1mdog2xkukqybyhasmrt.png" alt="Image description" width="671" height="736"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;All done now you should have a display as below&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1yuk31j8hob7u5qw4jee.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1yuk31j8hob7u5qw4jee.png" alt="Image description" width="644" height="770"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code on github Francis Kinyuru&lt;a href="https://github.com/franciskinyuru/Ussd-with-Africastalking-101" rel="noopener noreferrer"&gt;franciskinyuru&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Credits to &lt;br&gt;
&lt;strong&gt;Africastalking developers platform &lt;a href="https://developers.africastalking.com/" rel="noopener noreferrer"&gt;Developers platform&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Francis Kagai youtube tutorial &lt;a href="https://youtu.be/ml0mq-n1Ly0" rel="noopener noreferrer"&gt;Francis Kagai&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Python for everyone: Mastering Python the Right Way</title>
      <dc:creator>Francis kinyuru</dc:creator>
      <pubDate>Tue, 01 Mar 2022 13:22:02 +0000</pubDate>
      <link>https://dev.to/franciskinyuru/python-for-everyone-mastering-python-the-right-way-483d</link>
      <guid>https://dev.to/franciskinyuru/python-for-everyone-mastering-python-the-right-way-483d</guid>
      <description>&lt;h2&gt;
  
  
  What is Python?
&lt;/h2&gt;

&lt;p&gt;Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python is a general-purpose language, meaning it can be used to create a variety of different programs and isn't specialized for any specific problems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is python popular?&lt;/strong&gt;&lt;br&gt;
The python language is one of the most accessible programming languages available because it has simplified syntax and not complicated, which gives more emphasis on natural language. Due to its ease of learning and usage, python codes can be easily written and executed much faster than other programming languages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is the application areas of python?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Web and Internet Development&lt;/strong&gt;&lt;br&gt;
Python has many uses for web development including&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Django and Pyramid Frameworks for complex web apps&lt;/li&gt;
&lt;li&gt; Flask and Bottle micro-framework for light applications&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Scientific and Numeric&lt;/strong&gt;&lt;br&gt;
Widely used in scientific and numeric computing.&lt;br&gt;
This is in the fields of mathematics and Data science&lt;br&gt;
Popular libraries like scikit learn, pandas, NLTK, NumPy, SciPy used in data anaylis, machine-learning, AI, NLP and much more&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Education&lt;/strong&gt;&lt;br&gt;
Used for teaching programming both fundamentals and advanced levels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Software development&lt;/strong&gt;&lt;br&gt;
Used as a support language for software development, testing and build control&lt;/p&gt;

&lt;h2&gt;
  
  
  Best ways to learn python.
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Figure out why you need to learn python.&lt;/strong&gt;&lt;br&gt;
This acts as a driving force to what you need to achieve and setting the goals you want to achieve after running python.&lt;br&gt;
Pick an area you are interested in such as :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Data science / Machine learning&lt;/li&gt;
&lt;li&gt;Mobile apps&lt;/li&gt;
&lt;li&gt;Websites&lt;/li&gt;
&lt;li&gt;Games&lt;/li&gt;
&lt;li&gt;Data processing and analysis&lt;/li&gt;
&lt;li&gt;Hardware / Sensors / Robots&lt;/li&gt;
&lt;li&gt;Scripts to automate your work
Select one or two areas that interests you and which will eventually help in building projects with them.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Learn the basic Syntax.&lt;/strong&gt;&lt;br&gt;
This is key to any programming language. You have to understand the basic syntax to be able to come up with structured and more complex projects.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Come up with structured projects&lt;/strong&gt;&lt;br&gt;
This will help you apply knowledge you have learned and aids in opening you mind and digging deep to complex projects and will greatly help in your learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. More practice and more projects&lt;/strong&gt;&lt;br&gt;
Involve yourself in more projects and do more practice to master the concepts &lt;/p&gt;

&lt;h2&gt;
  
  
  Python installation and best practices
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Python Installation&lt;/strong&gt;&lt;br&gt;
Check the python documentation for installation on the various platforms &lt;a href="https://docs.python-guide.org/starting/installation/" rel="noopener noreferrer"&gt;Python Documentation&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Best practices&lt;/strong&gt;&lt;br&gt;
Also visit they python docs for best practice when writing you python code &lt;a href="https://docs.python-guide.org/writing/style/" rel="noopener noreferrer"&gt;DOCS&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;All the best in your python career. Happy Coding!!!💯&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Introduction to Data Structures and Algorithms With Python</title>
      <dc:creator>Francis kinyuru</dc:creator>
      <pubDate>Mon, 21 Feb 2022 13:00:47 +0000</pubDate>
      <link>https://dev.to/franciskinyuru/introduction-to-data-structures-and-algorithms-with-python-4ml8</link>
      <guid>https://dev.to/franciskinyuru/introduction-to-data-structures-and-algorithms-with-python-4ml8</guid>
      <description>&lt;h2&gt;
  
  
  What is Data Structures?
&lt;/h2&gt;

&lt;p&gt;This are containers that organize and group data according to type. &lt;br&gt;
Data Structures allows you to organize your data in such a way that enables you to store collections of data, relate them and perform operations on them accordingly. &lt;/p&gt;

&lt;p&gt;What are Algorithms?&lt;br&gt;
An algorithm is a set of instructions for solving a problem or accomplishing a task.&lt;/p&gt;

&lt;p&gt;Types of Data Structures&lt;br&gt;
&lt;strong&gt;In-built&lt;/strong&gt; &lt;br&gt;
Python has implicit support for Data Structures which enable you to store and access data. These structures are called List, Dictionary, Tuple and Set.&lt;br&gt;
&lt;strong&gt;User-defined&lt;/strong&gt;&lt;br&gt;
Python allows its users to create their own Data Structures enabling them to have full control over their functionality. The most prominent Data Structures are Stack, Queue, Tree, Linked List,Hashmap,Graph etc.&lt;/p&gt;
&lt;h2&gt;
  
  
  Built-in Data Structures
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;List
Lists are used to store data of different data types in a sequential manner. There are addresses assigned to every element of the list, which is called an Index. The index value starts from 0 and goes on until the last element called the positive index. There is also negative indexing which starts from -1 enabling you to access elements from the last to first element.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Creating a list&lt;/strong&gt;&lt;br&gt;
To create a list, you use the square brackets and add elements into it accordingly.&lt;br&gt;
If you dont pass any element in the list you get an empty list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myList = [] # create empty list
print(myList)
myList = [1,3,"john"] #creating list with data
print(myList)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;[]&lt;br&gt;
[1, 3, 'john']&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Adding Elements.&lt;br&gt;
Adding elements can be achieved by append(),insert(),extend() functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myList = [1,3,"john"]
print(myList)
myList.append(4) #add as a single element
print(myList)
myList.extend([10, 'more_example']) #add as different elements
print(myList)
myList.insert(3, 'insert_example') #add element i given position 
print(myList)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ouput &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;[1, 3, 'john']&lt;br&gt;
[1, 3, 'john', 4]&lt;br&gt;
[1, 3, 'john', 4, 10, 'more_example']&lt;br&gt;
[1, 3, 'john', 'insert_example', 4, 10, 'more_example']&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Deleting Elements&lt;/p&gt;

&lt;p&gt;If you want to delete an items to the list you can user del keyword, pop() or remove() functions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myList=[1, 3, 'insert_example', 4, 10, 'more_example']
del myList[2] #delete element at index 2
print(myList)
myList.remove('more_example') #remove element with value
print(myList)
a = myList.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', myList)
myList.clear() #empty the list
print(myList)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;[1, 3, 'john', 'insert_example', 4, 10, 'more_example']&lt;br&gt;
[1, 3, 4, 10, 'more_example']&lt;br&gt;
[1, 3, 4, 10]&lt;br&gt;
Popped Element:  3  List remaining:  [1, 4, 10]&lt;br&gt;
[]&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Accessing Elements&lt;br&gt;
 To access the values you pass the index of the values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myList = [1, 2, 3, 'john', 10, 15]
for element in myList: #access elements one by one
    print(element)
print(myList) #access all elements
print(myList[4]) #access index 4 element
print(myList[0:2]) #access elements from 0 to 1 and exclude 2
print(myList[::-1]) #access elements in reverse
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Ouput&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;1&lt;br&gt;
2&lt;br&gt;
3&lt;br&gt;
john&lt;br&gt;
10&lt;br&gt;
15&lt;br&gt;
[1, 2, 3, 'john', 10, 15]&lt;br&gt;
10&lt;br&gt;
[1, 2]&lt;br&gt;
[15, 10, 'john', 3, 2, 1]&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We other list functions which includes :-&lt;br&gt;
The len() function returns to us the length of the list.&lt;br&gt;
The index() function finds the index value of value passed where it has been encountered the first time.&lt;br&gt;
The count() function finds the count of the value passed to it.&lt;br&gt;
The sorted() and sort() functions do the same thing, that is to sort the values of the list. The sorted() has a return type whereas the sort() modifies the original list.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dictionary&lt;/strong&gt;&lt;br&gt;
Dictionaries are used to store key-value pairs.&lt;/p&gt;

&lt;p&gt;Creating a dictionary&lt;br&gt;
Dictionaries can be created using the calledbrackets or using the dict() function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myDict = {}  # empty dictionary
print(myDict)
myDict = {"key": "value", 1: "kenya", 2: "uganda"}  # with values
print(myDict)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;{}&lt;br&gt;
{'key': 'value', 1: 'kenya', 2: 'uganda'}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Changing and Adding key, value pairs&lt;br&gt;
To change the values of the dictionary, you need to do that using the keys. So, you firstly access the key and then change the value accordingly. To add values, you simply just add another key-value pair as shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myDict = {"key": "value", 1: "kenya", 2: "uganda"}  # with values
print(myDict)
myDict[1] = " Nigeria"  # access the key and give new  value
print(myDict)
myDict[3] = "Niger"  # adding a new key value pair
print(myDict)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;{'key': 'value', 1: 'kenya', 2: 'uganda'}&lt;br&gt;
{'key': 'value', 1: ' Nigeria', 2: 'uganda'}&lt;br&gt;
{'key': 'value', 1: ' Nigeria', 2: 'uganda', 3: 'Niger'}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Deleting key, value pairs&lt;/p&gt;

&lt;p&gt;To delete the values, you use the pop() function which returns the value that has been deleted.&lt;br&gt;
To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key and value.&lt;br&gt;
To clear the entire dictionary, you use the clear() function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myDict = {'key': 'value', 1: ' Nigeria', 2: 'uganda', 3: 'Niger'}
x = myDict.pop(3)  # pop element
print(x)
print(myDict)
y = myDict.popitem()  # empty dictionary
print(y)
print(myDict)
myDict.clear()
print(myDict)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;{'key': 'value', 1: ' Nigeria', 2: 'uganda', 3: 'Niger'}&lt;br&gt;
Niger&lt;br&gt;
{'key': 'value', 1: ' Nigeria', 2: 'uganda'}&lt;br&gt;
(2, 'uganda')&lt;br&gt;
{'key': 'value', 1: ' Nigeria'}&lt;br&gt;
{}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Accessing Elements&lt;br&gt;
You can access elements using the keys only. You can use either the get() function or just pass the key values and you will be retrieving the values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myDict = {'key': 'value', 1: ' Nigeria', 2: 'uganda', 3: 'Niger'}
print(myDict[1])  # access elements using keys
print(myDict.get(3))  # access using get()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Nigeria&lt;br&gt;
Niger&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;More functions &lt;br&gt;
Other Functions&lt;br&gt;
You have different functions which return  keys(), values(), items().&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myDict = {'key': 'value', 1: ' Nigeria', 2: 'uganda', 3: 'Niger'}
print(myDict.keys())  # get keys
print(myDict.values())  # get values
print(myDict.items())  # get key-value pairs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;dict_keys(['key', 1, 2, 3])&lt;br&gt;
dict_values(['value', ' Nigeria', 'uganda', 'Niger'])&lt;br&gt;
dict_items([('key', 'value'), (1, ' Nigeria'), (2, 'uganda'), (3, 'Niger')])&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Tuple&lt;/strong&gt;&lt;br&gt;
Tuples are the same as lists are with the exception that the data once entered into the tuple cannot be changed no matter what. The only exception is when the data inside the tuple is mutable, only then the tuple data can be changed&lt;/p&gt;

&lt;p&gt;Creating a Tuple&lt;br&gt;
You create a tuple using parenthesis or using the tuple() function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myTuple = (1, 2, 3) #create tuple
print(myTuple) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;(1, 2, 3)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Accessing Elements&lt;br&gt;
Accessing elements is the same as it is for accessing values in lists.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myTuple = (1, 2, 3,5)
for x in myTuple:
    print(x)
print(myTuple)
print(myTuple[0])
print(myTuple[:])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;1&lt;br&gt;
2&lt;br&gt;
3&lt;br&gt;
5&lt;br&gt;
(1, 2, 3, 5)&lt;br&gt;
1&lt;br&gt;
(1, 2, 3, 5)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Appending Elements&lt;br&gt;
To append the values, you use the ‘+’ operator which will take another tuple to be appended to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myTuple = (1, 2, 3,5)
myTuple=myTuple + (101,102,104,"now")
print(myTuple)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;(1, 2, 3, 5, 101, 102, 104, 'now')&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Sets&lt;/strong&gt;&lt;br&gt;
Sets are a collection of unordered elements that are unique. Meaning that even if the data is repeated more than one time, it would be entered into the set only once.&lt;/p&gt;

&lt;p&gt;Creating a set&lt;br&gt;
Sets are created using the Calledbrackets but instead of adding key-value pairs, you just pass values to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mySet={1,4,5,7,8,8,9,1,1}
print(mySet)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;{1, 4, 5, 7, 8, 9}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Adding elements&lt;br&gt;
To add elements, you use the add() function and pass the value to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mySet={1,4,5,7,8,8,9,1,1}
mySet.add("string ")
print(mySet)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;{1, 4, 5, 7, 8, 9, 'string '}&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Operations in sets&lt;br&gt;
The different operations on set such as union, intersection and so on are shown below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mySet = {1, 2, 3, 4}
mySet_2 = {3, 4, 5, 6}
print(mySet.union(mySet_2), '==', mySet | mySet_2) 
# union() function combines the data present in both sets.
print(mySet.intersection(mySet_2), '==', mySet &amp;amp; mySet_2) 
# intersection() function finds the data present in both sets only
print(mySet.difference(mySet_2), '==', mySet - mySet_2)  
# difference() function deletes the data present in both and outputs data present only in the set passed.
print(mySet.symmetric_difference(mySet_2), '==', mySet ^ mySet_2) # symmetric_difference() does the same as the difference() function but outputs the data which is remaining in both sets.
mySet.clear()
print(mySet)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;{1, 2, 3, 4, 5, 6} == {1, 2, 3, 4, 5, 6}&lt;br&gt;
{3, 4} == {3, 4}&lt;br&gt;
{1, 2} == {1, 2}&lt;br&gt;
{1, 2, 5, 6} == {1, 2, 5, 6}&lt;br&gt;
set()&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  User-Defined Data Structures
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Queue&lt;/strong&gt;&lt;br&gt;
A queue is a linear data structure which is based on the principle of First-In-First-Out (FIFO) where the data entered first will be accessed first. It is built using the array structure and has operations which can be performed from both ends of the Queue, that is, head-tail or front-back. Operations such as adding and deleting elements are called En-Queue and De-Queue and accessing the elements can be performed. Queues are used as Network Buffers for traffic congestion management, used in Operating Systems for Job Scheduling and many more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stack&lt;/strong&gt;&lt;br&gt;
Stacks are linear Data Structures which are based on the principle of Last-In-First-Out (LIFO) where data which is entered last will be the first to get accessed. It is built using the array structure and has operations namely, pushing (adding) elements, popping (deleting) elements and accessing elements only from one point in the stack called as the TOP. This TOP is the pointer to the current position of the stack. Stacks are prominently used in applications such as Recursive Programming, reversing words, undo mechanisms in word editors and more other applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Linked List&lt;/strong&gt;&lt;br&gt;
Linked lists are linear Data Structures which are not stored consequently but are linked with each other using pointers. The node of a linked list is composed of data and a pointer called next. These structures are most widely used in image viewing applications, music player applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Graph&lt;/strong&gt;&lt;br&gt;
Graphs are used to store data collection of points called vertices (nodes) and edges (edges). Graphs can be called as the most accurate representation of a real-world map. They are used to find the various cost-to-distance between the various data points called as the nodes and hence find the least path. Many applications such as Google Maps, Uber, and many more use Graphs to find the least distance and increase profits in the best ways.&lt;/p&gt;

</description>
      <category>datastructures</category>
      <category>python</category>
      <category>algorithms</category>
      <category>machinelearning</category>
    </item>
    <item>
      <title>Python 101:Introduction to Modern Python</title>
      <dc:creator>Francis kinyuru</dc:creator>
      <pubDate>Sat, 12 Feb 2022 08:41:13 +0000</pubDate>
      <link>https://dev.to/franciskinyuru/python-101introduction-to-modern-python-og0</link>
      <guid>https://dev.to/franciskinyuru/python-101introduction-to-modern-python-og0</guid>
      <description>&lt;p&gt;What is python?&lt;br&gt;
Python is an interpreted, general-language, high-level programming language invented by Guido van Rossum and was conceived in the late 1980s and released in 1991.&lt;/p&gt;

&lt;p&gt;Python is easy to read and write&lt;br&gt;
This is because since its syntax emphasizes readability thus easy and simple to read and write.&lt;/p&gt;

&lt;p&gt;Lets see what makes it simple.&lt;/p&gt;

&lt;p&gt;Sample helloworld.&lt;/p&gt;

&lt;p&gt;In PHP&lt;br&gt;
&lt;code&gt;&amp;lt;?php&lt;br&gt;
echo "Hello World!";&lt;br&gt;
?&amp;gt;&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Above is a three line code in Php.&lt;/p&gt;

&lt;p&gt;Lets see same code in Python.&lt;br&gt;
&lt;code&gt;print("Hello World!")&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
3 lines of code in PHP to one line of Code in python.&lt;/p&gt;

&lt;p&gt;Lets check how to install python in different environments &lt;/p&gt;

&lt;p&gt;Python installation steps&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;1. Visit &lt;a href="https://www.python.org/downloads/" rel="noopener noreferrer"&gt;https://www.python.org/downloads/&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;2. Select your Operating system(Windows,Linux/UNIX,MacOS,Other&lt;/li&gt;
&lt;li&gt;3. Select the release or version, click on it to download.&lt;/li&gt;
&lt;li&gt;Double click on the file to execute and install.
-- For window mark “add to system paths”
An alternative way to install python on Linux is to run sudo apt install python3 or sudo apt install python on the terminal.
For more check on the python &lt;a href="https://docs.python.org/" rel="noopener noreferrer"&gt;Documentation&lt;/a&gt;for more documentations.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lets now test our installation&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open Terminal on Linux or cmd on windows&lt;/li&gt;
&lt;li&gt;Run the python --version command to check if you installed the correct version.
If python is installed you will se something similar to below&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;C:\Users\Florida&amp;gt;python --version&lt;br&gt;
Python 3.10.2&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets now start learning python.&lt;br&gt;
On your terminal type Python hit enter and then type print("Hello Your_name!")&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;python &lt;br&gt;
print("hello your_name!")&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;See below expected output. Remember to use your name after hello&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F11wdwl0ug4jka85hkq8j.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F11wdwl0ug4jka85hkq8j.PNG" alt="Image description" width="800" height="96"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have different Platforms where you can start writing your codes on. Including Visual Studio code, Pycharm, Sublime-text and much more. Select a platform where you are best suited of and lets continue learning python.&lt;/p&gt;

&lt;p&gt;Lets see how Variables are declared also need to check on best practises guidelines on &lt;a href="https://www.python.org/dev/peps/pep-0008/" rel="noopener noreferrer"&gt;PEP 8 -- Style Guide for Python Code&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;Variables-are containers for storing data values.&lt;/p&gt;

&lt;p&gt;Python has no command for declaring a variable.&lt;br&gt;
A variable is created the moment you first assign a value to it&lt;/p&gt;

&lt;p&gt;Here i will be using pycharm to write my sample code.&lt;br&gt;
I have created a file example.py&lt;/p&gt;

&lt;p&gt;Have declared 2 variables as below.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;a = "I"&lt;br&gt;
b = 10&lt;br&gt;
print(a)&lt;br&gt;
print(b)&lt;br&gt;
&lt;/code&gt; &lt;br&gt;
See below expected output&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjcztn1cd7u9l8msz0bcm.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjcztn1cd7u9l8msz0bcm.PNG" alt="Image description" width="800" height="116"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Also you don't need to declare type.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;a ="I"  is of type str&lt;br&gt;
a =10 is of type int&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you need to know the type you just do as below&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;print(type(a))&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Output&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;class 'int'&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Casting &lt;br&gt;
This is done if you want to specify  the data type of your variable.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;a = int(10)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Case sensitive&lt;/p&gt;

&lt;p&gt;Note Variable names are case sensitive &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;a = 10&lt;br&gt;
A = "John"&lt;br&gt;
a cannot overwrite A since python is case sensitive &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let now check the type of variables:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Local variables &lt;/li&gt;
&lt;li&gt;Global Variables &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Local Variables:&lt;br&gt;
This are variables declared inside a function and without global keyword.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;def myfunc():&lt;br&gt;
 a="Francis"&lt;br&gt;
This variables are accessed inside but not outside the function.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Global Variables:&lt;/p&gt;

&lt;p&gt;This are variables created outside of a function and can be used by everyone, both inside of functions and outside.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a = "Kenya"
 def myfunc():
   print("I live in " + a)
myfunc()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I live in Kenya&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can also create a global variable using global keyword&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def myfunc():
    global a
    a = "kenya"

myfunc()
print(a)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Hope this guide gives you an Introduction to Python 101 .&lt;/p&gt;

&lt;p&gt;Let me know your thoughts in the comment section 👇&lt;/p&gt;

&lt;p&gt;Like, share and follow me 🚀 for more content.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
