Chumarat Pat

Chumarat Pat

1593239967

How to Use Fetch to Make AJAX Calls in JavaScript

I will be sharing bite sized learnings about JavaScript regularly in this series. We’ll cover JS fundamentals, browsers, DOM, system design, domain architecture and frameworks.

Fetch is an interface for making an AJAX request in JavaScript. It is implemented widely by modern browsers and is used to call an API.

const promise = fetch(url, [options])

Calling fetch returns a promise, with a Response object. The promise is rejected if there is a network error, and it’s resolved if there is no problem connecting to the server and the server responded a status code. This status code could be 200s, 400s or 500s.

A sample FETCH request -

fetch(url)
.then(response => response.json())
.catch(err => console.log(err))

The request is sent as a GET by default. To send a POST / PATCH / DELETE / PUT you can use the method property as part of options parameter. Some other possible values options can take -

  • method: such as GET, POST, PATCH
  • headers: Headers object
  • mode: such as corsno-corssame-origin
  • cache: cache mode for request
  • credentials
  • body

Example usage:

This example demonstrates the usage of fetch to call an API and to get a list of git repositories.

const url = 'https://api.github.com/users/shrutikapoor08/repos';

fetch(url)
  .then(response => response.json())
  .then(repos => {
    const reposList = repos.map(repo => repo.name);
    console.log(reposList);
  })
.catch(err => console.log(err))

To send a POST request, here’s how the method parameter can be used with async / await syntax.

const params = {
id: 123
}

const response = await fetch('url', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(params)
});

const data = await response.json();

#javascript #ajax

What is GEEK

Buddha Community

How to Use Fetch to Make AJAX Calls in JavaScript
Chloe  Butler

Chloe Butler

1667425440

Pdf2gerb: Perl Script Converts PDF Files to Gerber format

pdf2gerb

Perl script converts PDF files to Gerber format

Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.

The general workflow is as follows:

  1. Design the PCB using your favorite CAD or drawing software.
  2. Print the top and bottom copper and top silk screen layers to a PDF file.
  3. Run Pdf2Gerb on the PDFs to create Gerber and Excellon files.
  4. Use a Gerber viewer to double-check the output against the original PCB design.
  5. Make adjustments as needed.
  6. Submit the files to a PCB manufacturer.

Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).

See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.


pdf2gerb_cfg.pm

#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;

use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)


##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file

use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call

#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software.  \nGerber files MAY CONTAIN ERRORS.  Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG

use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC

use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)

#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1); 

#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
    .010, -.001,  #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
    .031, -.014,  #used for vias
    .041, -.020,  #smallest non-filled plated hole
    .051, -.025,
    .056, -.029,  #useful for IC pins
    .070, -.033,
    .075, -.040,  #heavier leads
#    .090, -.043,  #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
    .100, -.046,
    .115, -.052,
    .130, -.061,
    .140, -.067,
    .150, -.079,
    .175, -.088,
    .190, -.093,
    .200, -.100,
    .220, -.110,
    .160, -.125,  #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
    .090, -.040,  #want a .090 pad option, but use dummy hole size
    .065, -.040, #.065 x .065 rect pad
    .035, -.040, #.035 x .065 rect pad
#traces:
    .001,  #too thin for real traces; use only for board outlines
    .006,  #minimum real trace width; mainly used for text
    .008,  #mainly used for mid-sized text, not traces
    .010,  #minimum recommended trace width for low-current signals
    .012,
    .015,  #moderate low-voltage current
    .020,  #heavier trace for power, ground (even if a lighter one is adequate)
    .025,
    .030,  #heavy-current traces; be careful with these ones!
    .040,
    .050,
    .060,
    .080,
    .100,
    .120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);

#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size:   parsed PDF diameter:      error:
#  .014                .016                +.002
#  .020                .02267              +.00267
#  .025                .026                +.001
#  .029                .03167              +.00267
#  .033                .036                +.003
#  .040                .04267              +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
    HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
    RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
    SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
    RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
    TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
    REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};

#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
    CIRCLE_ADJUST_MINX => 0,
    CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
    CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
    CIRCLE_ADJUST_MAXY => 0,
    SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
    WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
    RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};

#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches

#line join/cap styles:
use constant
{
    CAP_NONE => 0, #butt (none); line is exact length
    CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
    CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
    CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
    
#number of elements in each shape type:
use constant
{
    RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
    LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
    CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
    CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
    rect => RECT_SHAPELEN,
    line => LINE_SHAPELEN,
    curve => CURVE_SHAPELEN,
    circle => CIRCLE_SHAPELEN,
);

#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions

# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?

#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes. 
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes

#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches

# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)

# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time

# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const

use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool

my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time

print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load


#############################################################################################
#junk/experiment:

#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html

#my $caller = "pdf2gerb::";

#sub cfg
#{
#    my $proto = shift;
#    my $class = ref($proto) || $proto;
#    my $settings =
#    {
#        $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
#    };
#    bless($settings, $class);
#    return $settings;
#}

#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;

#print STDERR "read cfg file\n";

#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names

#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }

Download Details:

Author: swannman
Source Code: https://github.com/swannman/pdf2gerb

License: GPL-3.0 license

#perl 

坂本  篤司

坂本 篤司

1652450700

Pythonグローバル変数–グローバル変数の例を定義する方法

この記事では、グローバル変数の基本を学びます。

まず、Pythonで変数を宣言する方法と、「変数スコープ」という用語が実際に何を意味するかを学習します。

次に、ローカル変数とグローバル変数の違いを学び、グローバル変数の定義方法とglobalキーワードの使用方法を理解します。

Pythonの変数とは何ですか?どのように作成しますか?初心者のための紹介

変数はストレージコンテナと考えることができます。

これらは、コンピュータのメモリに保存したいデータ、情報、および値を保持するためのストレージコンテナです。その後、プログラムの存続期間中のある時点でそれらを参照したり、操作したりすることもできます。

変数にはシンボリックがあり、その名前は、その識別子として機能するストレージコンテナのラベルと考えることができます。

変数名は、その中に格納されているデータへの参照とポインターになります。したがって、データと情報の詳細を覚えておく必要はありません。そのデータと情報を保持する変数名を参照するだけで済みます。

変数に名前を付けるときは、変数が保持するデータを説明していることを確認してください。変数名は、将来の自分自身と一緒に作業する可能性のある他の開発者の両方にとって、明確で簡単に理解できる必要があります。

それでは、Pythonで実際に変数を作成する方法を見てみましょう。

Pythonで変数を宣言するときは、データ型を指定する必要はありません。

たとえば、Cプログラミング言語では、変数が保持するデータの型を明示的に指定する必要があります。

したがって、整数またはint型である年齢を格納したい場合、これはCで行う必要があることです。

#include <stdio.h>
 
int main(void)
{
  int age = 28;
  // 'int' is the data type
  // 'age' is the name 
  // 'age' is capable of holding integer values
  // positive/negative whole numbers or 0
  // '=' is the assignment operator
  // '28' is the value
}

ただし、これはPythonで上記を記述する方法です。

age = 28

#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'

変数名は常に左側にあり、代入する値は代入演算子の後に右側に配置されます。

プログラムの存続期間中、変数の値を変更できることに注意してください。

my_age = 28

print(f"My age in 2022 is {my_age}.")

my_age = 29

print(f"My age in 2023 will be {my_age}.")

#output

#My age in 2022 is 28.
#My age in 2023 will be 29.

同じ変数名を保持しますが、値をからにmy_age変更するだけです。2829

Pythonの可変スコープとはどういう意味ですか?

変数スコープとは、変数が利用可能で、アクセス可能で、表示可能なPythonプログラムの部分と境界を指します。

Python変数のスコープには4つのタイプがあり、 LEGBルールとも呼ばれます。

  • 局所
  • 囲み
  • グローバル
  • ビルトイン

この記事の残りの部分では、グローバルスコープを使用した変数の作成について学習することに焦点を当て、ローカル変数スコープとグローバル変数スコープの違いを理解します。

Pythonでローカルスコープを使用して変数を作成する方法

関数の本体内で定義された変数にはローカルスコープがあります。つまり、その特定の関数内でのみアクセスできます。言い換えれば、それらはその関数に対して「ローカル」です。

ローカル変数にアクセスするには、関数を呼び出す必要があります。

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()


#output

#The best place to learn to code is with freeCodeCamp!

関数の本体の外部からローカルスコープを使用してその変数にアクセスしようとするとどうなるかを見てください。

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#try to print local variable 'coding_website' from outside the function
print(coding_website)

#output

#NameError: name 'coding_website' is not defined

NameErrorプログラムの残りの部分では「表示」されないため、aが発生します。定義された関数内でのみ「表示」されます。

Pythonでグローバルスコープを使用して変数を作成する方法

ファイルの先頭など、関数の外部で変数を定義すると、その変数はグローバルスコープを持ち、グローバル変数と呼ばれます。

グローバル変数は、プログラムのどこからでもアクセスできます。

関数の本体内で使用することも、関数の外部からアクセスすることもできます。

#create a global variable
coding_website = "freeCodeCamp"

def learn_to_code():
    #access the variable 'coding_website' inside the function
    print(f"The best place to learn to code is with {coding_website}!")

#call the function
learn_to_code()

#access the variable 'coding_website' from outside the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

グローバル変数とローカル変数があり、両方が同じ名前の場合はどうなりますか?

#global variable
city = "Athens"

def travel_plans():
    #local variable with the same name as the global variable
    city = "London"
    print(f"I want to visit {city} next year!")

#call function - this will output the value of local variable
travel_plans()

#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")

#output

#I want to visit London next year!
#I want to visit Athens next year!

上記の例では、その特定の出力を期待していなかった可能性があります。

city関数内で別の値を割り当てたときに、の値が変わると思ったかもしれません。

たぶん、私が行でグローバル変数を参照したときprint(f" I want to visit {city} next year!")、出力は#I want to visit London next year!の代わりになると予想しました#I want to visit Athens next year!

ただし、関数が呼び出されると、ローカル変数の値が出力されます。

次に、関数の外部でグローバル変数を参照すると、グローバル変数に割り当てられた値が出力されました。

彼らはお互いに干渉しませんでした。

ただし、グローバル変数とローカル変数に同じ変数名を使用することは、ベストプラクティスとは見なされません。プログラムを実行すると混乱する結果が生じる可能性があるため、変数の名前が同じでないことを確認してください。

Pythonでキーワードを使用する方法global

グローバル変数があり、関数内でその値を変更したい場合はどうなりますか?

私がそれをしようとすると何が起こるか見てください:

#global variable
city = "Athens"

def travel_plans():
    #First, this is like when I tried to access the global variable defined outside the function. 
    # This works fine on its own, as you saw earlier on.
    print(f"I want to visit {city} next year!")

    #However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
    #after trying to print it,
    #it will throw an error
    city = "London"
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#output

#UnboundLocalError: local variable 'city' referenced before assignment

デフォルトでは、Pythonは関数内でローカル変数を使用したいと考えています。

そのため、最初に変数の値を出力してから、アクセスしようとしている変数に値再割り当てしようとすると、Pythonが混乱します。

関数内のグローバル変数の値を変更する方法は、次のglobalキーワードを使用することです。

#global variable
city = "Athens"

#print value of global variable
print(f"I want to visit {city} next year!")

def travel_plans():
    global city
    #print initial value of global variable
    print(f"I want to visit {city} next year!")
    #assign a different value to global variable from within function
    city = "London"
    #print new value
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#print value of global variable
print(f"I want to visit {city} next year!")

global次のエラーが発生するため、関数でキーワードを参照する前にキーワードを使用してくださいSyntaxError: name 'city' is used prior to global declaration

以前、関数内で作成された変数はローカルスコープを持っているため、それらにアクセスできないことを確認しました。

globalキーワードは、関数内で宣言された変数の可視性を変更します。

def learn_to_code():
   global coding_website
   coding_website = "freeCodeCamp"
   print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()

#access variable from within the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

結論

そして、あなたはそれを持っています!これで、Pythonのグローバル変数の基本を理解し、ローカル変数とグローバル変数の違いを理解できます。

この記事がお役に立てば幸いです。

基本から始めて、インタラクティブで初心者に優しい方法で学びます。また、最後に5つのプロジェクトを構築して実践し、学んだことを強化するのに役立てます。

読んでくれてありがとう、そして幸せなコーディング!

ソース:https ://www.freecodecamp.org/news/python-global-variables-examples/

#python 

Variables Globales De Python: Cómo Definir Un Ejemplo De Variable Glob

En este artículo, aprenderá los conceptos básicos de las variables globales.

Para empezar, aprenderá cómo declarar variables en Python y qué significa realmente el término 'ámbito de variable'.

Luego, aprenderá las diferencias entre variables locales y globales y comprenderá cómo definir variables globales y cómo usar la globalpalabra clave.

¿Qué son las variables en Python y cómo se crean? Una introducción para principiantes

Puede pensar en las variables como contenedores de almacenamiento .

Son contenedores de almacenamiento para almacenar datos, información y valores que le gustaría guardar en la memoria de la computadora. Luego puede hacer referencia a ellos o incluso manipularlos en algún momento a lo largo de la vida del programa.

Una variable tiene un nombre simbólico y puede pensar en ese nombre como la etiqueta en el contenedor de almacenamiento que actúa como su identificador.

El nombre de la variable será una referencia y un puntero a los datos almacenados en su interior. Por lo tanto, no es necesario recordar los detalles de sus datos e información; solo necesita hacer referencia al nombre de la variable que contiene esos datos e información.

Al dar un nombre a una variable, asegúrese de que sea descriptivo de los datos que contiene. Los nombres de las variables deben ser claros y fácilmente comprensibles tanto para usted en el futuro como para los otros desarrolladores con los que puede estar trabajando.

Ahora, veamos cómo crear una variable en Python.

Al declarar variables en Python, no necesita especificar su tipo de datos.

Por ejemplo, en el lenguaje de programación C, debe mencionar explícitamente el tipo de datos que contendrá la variable.

Entonces, si quisiera almacenar su edad, que es un número entero, o inttipo, esto es lo que tendría que hacer en C:

#include <stdio.h>
 
int main(void)
{
  int age = 28;
  // 'int' is the data type
  // 'age' is the name 
  // 'age' is capable of holding integer values
  // positive/negative whole numbers or 0
  // '=' is the assignment operator
  // '28' is the value
}

Sin embargo, así es como escribirías lo anterior en Python:

age = 28

#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'

El nombre de la variable siempre está en el lado izquierdo y el valor que desea asignar va en el lado derecho después del operador de asignación.

Tenga en cuenta que puede cambiar los valores de las variables a lo largo de la vida de un programa:

my_age = 28

print(f"My age in 2022 is {my_age}.")

my_age = 29

print(f"My age in 2023 will be {my_age}.")

#output

#My age in 2022 is 28.
#My age in 2023 will be 29.

Mantienes el mismo nombre de variable my_age, pero solo cambias el valor de 28a 29.

¿Qué significa el alcance variable en Python?

El alcance de la variable se refiere a las partes y los límites de un programa de Python donde una variable está disponible, accesible y visible.

Hay cuatro tipos de alcance para las variables de Python, que también se conocen como la regla LEGB :

  • local ,
  • Encerrando ,
  • globales ,
  • Incorporado .

En el resto de este artículo, se centrará en aprender a crear variables con alcance global y comprenderá la diferencia entre los alcances de variables locales y globales.

Cómo crear variables con alcance local en Python

Las variables definidas dentro del cuerpo de una función tienen alcance local , lo que significa que solo se puede acceder a ellas dentro de esa función en particular. En otras palabras, son 'locales' para esa función.

Solo puede acceder a una variable local llamando a la función.

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()


#output

#The best place to learn to code is with freeCodeCamp!

Mire lo que sucede cuando trato de acceder a esa variable con un alcance local desde fuera del cuerpo de la función:

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#try to print local variable 'coding_website' from outside the function
print(coding_website)

#output

#NameError: name 'coding_website' is not defined

Plantea un NameErrorporque no es 'visible' en el resto del programa. Solo es 'visible' dentro de la función donde se definió.

Cómo crear variables con alcance global en Python

Cuando define una variable fuera de una función, como en la parte superior del archivo, tiene un alcance global y se conoce como variable global.

Se accede a una variable global desde cualquier parte del programa.

Puede usarlo dentro del cuerpo de una función, así como acceder desde fuera de una función:

#create a global variable
coding_website = "freeCodeCamp"

def learn_to_code():
    #access the variable 'coding_website' inside the function
    print(f"The best place to learn to code is with {coding_website}!")

#call the function
learn_to_code()

#access the variable 'coding_website' from outside the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

¿Qué sucede cuando hay una variable global y local, y ambas tienen el mismo nombre?

#global variable
city = "Athens"

def travel_plans():
    #local variable with the same name as the global variable
    city = "London"
    print(f"I want to visit {city} next year!")

#call function - this will output the value of local variable
travel_plans()

#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")

#output

#I want to visit London next year!
#I want to visit Athens next year!

En el ejemplo anterior, tal vez no esperaba ese resultado específico.

Tal vez pensaste que el valor de citycambiaría cuando le asignara un valor diferente dentro de la función.

Tal vez esperabas que cuando hice referencia a la variable global con la línea print(f" I want to visit {city} next year!"), la salida sería en #I want to visit London next year!lugar de #I want to visit Athens next year!.

Sin embargo, cuando se llamó a la función, imprimió el valor de la variable local.

Luego, cuando hice referencia a la variable global fuera de la función, se imprimió el valor asignado a la variable global.

No interfirieron entre sí.

Dicho esto, usar el mismo nombre de variable para variables globales y locales no se considera una buena práctica. Asegúrese de que sus variables no tengan el mismo nombre, ya que puede obtener algunos resultados confusos cuando ejecute su programa.

Cómo usar la globalpalabra clave en Python

¿Qué sucede si tiene una variable global pero desea cambiar su valor dentro de una función?

Mira lo que sucede cuando trato de hacer eso:

#global variable
city = "Athens"

def travel_plans():
    #First, this is like when I tried to access the global variable defined outside the function. 
    # This works fine on its own, as you saw earlier on.
    print(f"I want to visit {city} next year!")

    #However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
    #after trying to print it,
    #it will throw an error
    city = "London"
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#output

#UnboundLocalError: local variable 'city' referenced before assignment

Por defecto, Python piensa que quieres usar una variable local dentro de una función.

Entonces, cuando intento imprimir el valor de la variable por primera vez y luego reasignar un valor a la variable a la que intento acceder, Python se confunde.

La forma de cambiar el valor de una variable global dentro de una función es usando la globalpalabra clave:

#global variable
city = "Athens"

#print value of global variable
print(f"I want to visit {city} next year!")

def travel_plans():
    global city
    #print initial value of global variable
    print(f"I want to visit {city} next year!")
    #assign a different value to global variable from within function
    city = "London"
    #print new value
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#print value of global variable
print(f"I want to visit {city} next year!")

Utilice la globalpalabra clave antes de hacer referencia a ella en la función, ya que obtendrá el siguiente error: SyntaxError: name 'city' is used prior to global declaration.

Anteriormente, vio que no podía acceder a las variables creadas dentro de las funciones ya que tienen un alcance local.

La globalpalabra clave cambia la visibilidad de las variables declaradas dentro de las funciones.

def learn_to_code():
   global coding_website
   coding_website = "freeCodeCamp"
   print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()

#access variable from within the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

Conclusión

¡Y ahí lo tienes! Ahora conoce los conceptos básicos de las variables globales en Python y puede distinguir las diferencias entre las variables locales y globales.

Espero que hayas encontrado útil este artículo.

Comenzará desde lo básico y aprenderá de una manera interactiva y amigable para principiantes. También construirá cinco proyectos al final para poner en práctica y ayudar a reforzar lo que ha aprendido.

¡Gracias por leer y feliz codificación!

Fuente: https://www.freecodecamp.org/news/python-global-variables-examples/

#python 

Python Global Variables – How to Define a Global Variable Example

In this article, you will learn the basics of global variables.

To begin with, you will learn how to declare variables in Python and what the term 'variable scope' actually means.

Then, you will learn the differences between local and global variables and understand how to define global variables and how to use the global keyword.

What Are Variables in Python and How Do You Create Them? An Introduction for Beginners

You can think of variables as storage containers.

They are storage containers for holding data, information, and values that you would like to save in the computer's memory. You can then reference or even manipulate them at some point throughout the life of the program.

A variable has a symbolic name, and you can think of that name as the label on the storage container that acts as its identifier.

The variable name will be a reference and pointer to the data stored inside it. So, there is no need to remember the details of your data and information – you only need to reference the variable name that holds that data and information.

When giving a variable a name, make sure that it is descriptive of the data it holds. Variable names need to be clear and easily understandable both for your future self and the other developers you may be working with.

Now, let's see how to actually create a variable in Python.

When declaring variables in Python, you don't need to specify their data type.

For example, in the C programming language, you have to mention explicitly the type of data the variable will hold.

So, if you wanted to store your age which is an integer, or int type, this is what you would have to do in C:

#include <stdio.h>
 
int main(void)
{
  int age = 28;
  // 'int' is the data type
  // 'age' is the name 
  // 'age' is capable of holding integer values
  // positive/negative whole numbers or 0
  // '=' is the assignment operator
  // '28' is the value
}

However, this is how you would write the above in Python:

age = 28

#'age' is the variable name, or identifier
# '=' is the assignment operator
#'28' is the value assigned to the variable, so '28' is the value of 'age'

The variable name is always on the left-hand side, and the value you want to assign goes on the right-hand side after the assignment operator.

Keep in mind that you can change the values of variables throughout the life of a program:

my_age = 28

print(f"My age in 2022 is {my_age}.")

my_age = 29

print(f"My age in 2023 will be {my_age}.")

#output

#My age in 2022 is 28.
#My age in 2023 will be 29.

You keep the same variable name, my_age, but only change the value from 28 to 29.

What Does Variable Scope in Python Mean?

Variable scope refers to the parts and boundaries of a Python program where a variable is available, accessible, and visible.

There are four types of scope for Python variables, which are also known as the LEGB rule:

  • Local,
  • Enclosing,
  • Global,
  • Built-in.

For the rest of this article, you will focus on learning about creating variables with global scope, and you will understand the difference between the local and global variable scopes.

How to Create Variables With Local Scope in Python

Variables defined inside a function's body have local scope, which means they are accessible only within that particular function. In other words, they are 'local' to that function.

You can only access a local variable by calling the function.

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()


#output

#The best place to learn to code is with freeCodeCamp!

Look at what happens when I try to access that variable with a local scope from outside the function's body:

def learn_to_code():
    #create local variable
    coding_website = "freeCodeCamp"
    print(f"The best place to learn to code is with {coding_website}!")

#try to print local variable 'coding_website' from outside the function
print(coding_website)

#output

#NameError: name 'coding_website' is not defined

It raises a NameError because it is not 'visible' in the rest of the program. It is only 'visible' within the function where it was defined.

How to Create Variables With Global Scope in Python

When you define a variable outside a function, like at the top of the file, it has a global scope and it is known as a global variable.

A global variable is accessed from anywhere in the program.

You can use it inside a function's body, as well as access it from outside a function:

#create a global variable
coding_website = "freeCodeCamp"

def learn_to_code():
    #access the variable 'coding_website' inside the function
    print(f"The best place to learn to code is with {coding_website}!")

#call the function
learn_to_code()

#access the variable 'coding_website' from outside the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

What happens when there is a global and local variable, and they both have the same name?

#global variable
city = "Athens"

def travel_plans():
    #local variable with the same name as the global variable
    city = "London"
    print(f"I want to visit {city} next year!")

#call function - this will output the value of local variable
travel_plans()

#reference global variable - this will output the value of global variable
print(f"I want to visit {city} next year!")

#output

#I want to visit London next year!
#I want to visit Athens next year!

In the example above, maybe you were not expecting that specific output.

Maybe you thought that the value of city would change when I assigned it a different value inside the function.

Maybe you expected that when I referenced the global variable with the line print(f" I want to visit {city} next year!"), the output would be #I want to visit London next year! instead of #I want to visit Athens next year!.

However, when the function was called, it printed the value of the local variable.

Then, when I referenced the global variable outside the function, the value assigned to the global variable was printed.

They didn't interfere with one another.

That said, using the same variable name for global and local variables is not considered a best practice. Make sure that your variables don't have the same name, as you may get some confusing results when you run your program.

How to Use the global Keyword in Python

What if you have a global variable but want to change its value inside a function?

Look at what happens when I try to do that:

#global variable
city = "Athens"

def travel_plans():
    #First, this is like when I tried to access the global variable defined outside the function. 
    # This works fine on its own, as you saw earlier on.
    print(f"I want to visit {city} next year!")

    #However, when I then try to re-assign a different value to the global variable 'city' from inside the function,
    #after trying to print it,
    #it will throw an error
    city = "London"
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#output

#UnboundLocalError: local variable 'city' referenced before assignment

By default Python thinks you want to use a local variable inside a function.

So, when I first try to print the value of the variable and then re-assign a value to the variable I am trying to access, Python gets confused.

The way to change the value of a global variable inside a function is by using the global keyword:

#global variable
city = "Athens"

#print value of global variable
print(f"I want to visit {city} next year!")

def travel_plans():
    global city
    #print initial value of global variable
    print(f"I want to visit {city} next year!")
    #assign a different value to global variable from within function
    city = "London"
    #print new value
    print(f"I want to visit {city} next year!")

#call function
travel_plans()

#print value of global variable
print(f"I want to visit {city} next year!")

Use the global keyword before referencing it in the function, as you will get the following error: SyntaxError: name 'city' is used prior to global declaration.

Earlier, you saw that you couldn't access variables created inside functions since they have local scope.

The global keyword changes the visibility of variables declared inside functions.

def learn_to_code():
   global coding_website
   coding_website = "freeCodeCamp"
   print(f"The best place to learn to code is with {coding_website}!")

#call function
learn_to_code()

#access variable from within the function
print(coding_website)

#output

#The best place to learn to code is with freeCodeCamp!
#freeCodeCamp

Conclusion

And there you have it! You now know the basics of global variables in Python and can tell the differences between local and global variables.

I hope you found this article useful.

You'll start from the basics and learn in an interactive and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you've learned.

Thanks for reading and happy coding!

Source: https://www.freecodecamp.org/news/python-global-variables-examples/

#python 

Making AJAX Calls using the Fetch API

In this post we’ll do everything we did in the second post, but with Fetch API.

What’s this Fetch API?

The almighty docs say

The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest but the new API provides a more powerful and flexible feature set.

I prepared this demo page so that you can test.

You’ll remember from the last post that in order to make an AJAX call with jQuery, you have to do something like this:

$('#result').load('http://nikola-breznjak.com/_testings/ajax/test1.php?ime=Nikola');

Go ahead and run that code on the demo page in the browser’s dev tools Console

Now, the very same thing with the Fetch API looks like this:

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
fetch(link)
    .then(function(response){
        return response.json()
    })
    .then(function(result){
        var oglasiHTML = '';
        $.each(result, function(index, oglas){
            var klasaCijene = '';
            if (oglas.cijena < 100){
                klasaCijene = 'is-success';
            }
            else if (oglas.cijena >= 100 && oglas.cijena < 300){
                klasaCijene = 'is-info';
            }
            else if (oglas.cijena >= 300){
                klasaCijene = 'is-danger';
            }
 
            oglasiHTML += `
                <div class="columns">
                    <div class="column is-one-quarter">
                        <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                    </div>
                    <div class="column">${oglas.tekst}</div>
                </div>
            `;
        });
 
        $('#oglasi').html(oglasiHTML);
    });

Go ahead and try it in the Console. Change the ime parameter, and you’ll see that the text on the page will change to Hello [name], where [name] will be the parameter you entered. Note that in the example above I still used jQuery to set the content of the div with id result.

The docs have way more info on this but, as they say, the difference between fetch() and $.ajax() is in two main things:

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  • By default, fetch() won’t send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

⚠️ At a later point you may want to read a bit more about Promises in Javascript.

Rewriting the mini project

I encourage you to try it for yourself and then check your solution to mine.

The mini project (which you can test here) would be rewritten like this:

var link = 'http://nikola-breznjak.com/_testings/ajax/test2.php';
fetch(link)
    .then(function(response){
        return response.json()
    })
    .then(function(result){
        var oglasiHTML = '';
        $.each(result, function(index, oglas){
            var klasaCijene = '';
            if (oglas.cijena < 100){
                klasaCijene = 'is-success';
            }
            else if (oglas.cijena >= 100 && oglas.cijena < 300){
                klasaCijene = 'is-info';
            }
            else if (oglas.cijena >= 300){
                klasaCijene = 'is-danger';
            }
 
            oglasiHTML += `
                <div class="columns">
                    <div class="column is-one-quarter">
                        <span class="tag ${klasaCijene}">${oglas.cijena}</span>
                    </div>
                    <div class="column">${oglas.tekst}</div>
                </div>
            `;
        });
 
        $('#oglasi').html(oglasiHTML);
    });

There are a few things that I’d like to point out here:

  • I used the response.json() because I know that this API returns a JSON response (you can check by opening that link in the browser).
  • I used the jQuery each function to iterate over the result.
  • I used the template literals to construct the final oglasiHTML in a much cleaner way than we did that in the previous post with using concatenation.

#javascript #api #fetch #ajax