Moli Ena

1583925761

Discord Screen Share and Video call: A Complete, 10-Step Guide

Originally Published at Troop Messenger

If you play PC games online, it’s safe to assume that you are familiar with Discord.

If not, this article can be a great resource because Discord has some of the best screen-sharing features, which can benefit both gamers and non-gamers.

You and up to 9 friends can simultaneously screen share on the discord server. At one time, 10 Discord users can conduct a live video chat, while they all are sharing their desktop screens, simultaneously.

Discord Screen Share feature has made Discord an incredibly powerful software for virtual collaboration, especially for teams that require online meetings and video calling from remote locations.

Discord has literally changed the way video conferences work. It’s peak concurrent users recently topped at 8.2 million.

Since Discord is spreading its wings as a real competitor of business communication and collaboration tools, we’ve got quite a few queries on ‘How to share screen on discord.’

In this article, we are going to show you 10 Easy-to-follow steps to configuring and using video calling and screen sharing feature of Discord:

What is Discord Application?
Discord is inarguably one of the most commonly used communication tools for online streaming and gaming.

Essentially, it’s a Skype Alternative for gamers, that is specifically designed to help the gamers coordinate and communicate through private servers which allow users to voice-chat and text with other people.

Discord application primarily functions with mobile and desktop platforms, and combines the features of:

A message board
A chat room
A VoIP chatting system

Discord’s popularity has increased over the past few years and the app has over 250 million registered users.

Discord Screen Share
One of the most powerful features of Discord is Screen Sharing, which was added in August 2017. The screen sharing feature allows users on the Discord chat server to view and interact with your screen.

Alongside the screen sharing, you can also conduct video calling, simultaneously, on the chat servers that is a great in-built feature of Discord. The users do not need to install another software, a discord screen share extension or integrate a third-party application

Screen Sharing & Video Camera Features: On Desktop

If you are using Discord on PC, you can avail the following features:

  1. Share Sound:
    While you are sharing your discord or computer screen on Discord Server, you can also opt-out of sound sharing. This feature helps a great deal when you’re in a public place, and you want to cut down on the background noise to avoid disturbance.

You can opt-in or opt-out of sound sharing by toggling the sound icon between Off and On.

  1. Swap from Screen Share to Video:
    An icon located at the bottom of the video screen enables Discord users to swap from a screen share to only video calling, and vice versa.

At anytime during the conversation, you can swap between the two. When swapping your computer screen, you can opt for which monitor screen to share. You can also opt for sharing only a specific application window.

  1. Video Marquee
    Discord Users who wish to see only a specific video and opt-out of seeing others can make use of the Video Marquee feature.

For this, you’d need to click on the user’s avatar, which will make the video to pop-out among others.

Screen Sharing & Video Camera Features: On Smartphone
If you are using Discord on your smartphone, you can avail the following features :

Unfortunately, the screen sharing feature is not available for Discord Smartphone users. So, you cannot avail of discord screen share for mobile.

Toggle Mute:

Should you wish to tune-out of the background or surrounding noise, the Toggle Mute feature can be a savior.

In the smartphone version of Discord, a user when on a video call, can mute their phone’s mic to prevent the outgoing sound on a chat server.

Tune Camera:

While making a video call through Discord mobile app, you can tune your camera, start and stop it from functioning at any time.

Similarly, there’s also an option to switch from front to back camera, and vice versa.

Audio Output (only for iOS):
This is an exclusive feature for Discord’s iPhone application. Audio Output is located on the top-right corner, next to the Switch Camera icon.

Using this, you can swap the audio output between your wireless headset or iPhone’s default speaker.

Step-by-Step Guide For Video Calling With Some Hacks
In this section, you’ll learn about the different ways to share your computer screen with another discord user.

To initiate video calling and screen sharing, install the Discord Application in your device, and configure video and audio hardware on Discord client.

a) Camera Settings

Step 1: Find the ‘Setting’ icon at the bottom left side of your screen, and click on the settings.

Step 2: To adjust your Video and Voice chat settings, look for the ‘Voice and Video’ Option under the ‘App Settings’ category on the left-hand menu.

Step 3: Should you wish to change the video settings, scroll down to find ‘Video Settings’ and opt for ‘Video Camera Hardware’. You can also do a test video.

b) Connecting with Users
Step 4: On the top-left panel, find Discord icon, and navigate to ‘Homepage.’ Click on the ‘Friends’ icon to open the list of friends on your discord server.

Step 5: Hover over the user’s name, and opt for Video calling.

Step 6: Click on the Video icon to enable a video conference with the user

Step-by-Step Guide For Discord Screen Sharing With Some Hacks
For discord screen share in the server, you’d need to initiate a Video call using the steps defined above.

Let’s proceed to Step 6 and see how you can enable screen sharing via Discord, and peek into your friend’s desktop.

Step 7: As the video calling is in process, look for a screen sharing icon present on the bottom of your screen. You can identify a screen-sharing icon that resembles a computer display with an arrow at the center.

Step 8: Click on this icon to enable screen sharing of your PC, and opt between sharing ‘Your Entire Screen’ or ‘Application Window.’

Step 9: You can further interchange share screen discord and video calling features by clicking on the same icon.

Step 10: To Stop sharing the screen, you can hover back to the ‘screen share’ icon and opt for ‘More Screen Share Options,’ and ‘Turn Off Screen Sharing.’

#discord video call

What is GEEK

Buddha Community

Discord Screen Share and Video call: A Complete, 10-Step Guide
John  Smith

John Smith

1657107416

Find the Best Restaurant Mobile App Development Company in Abu Dhbai

The era of mobile app development has completely changed the scenario for businesses in regions like Abu Dhabi. Restaurants and food delivery businesses are experiencing huge benefits via smart business applications. The invention and development of the food ordering app have helped all-scale businesses reach new customers and boost sales and profit. 

As a result, many business owners are searching for the best restaurant mobile app development company in Abu Dhabi. If you are also searching for the same, this article is helpful for you. It will let you know the step-by-step process to hire the right team of restaurant mobile app developers. 

Step-by-Step Process to Find the Best Restaurant App Development Company

Searching for the top mobile app development company in Abu Dhabi? Don't know the best way to search for professionals? Don't panic! Here is the step-by-step process to hire the best professionals. 

#Step 1 – Know the Company's Culture

Knowing the organization's culture is very crucial before finalizing a food ordering app development company in Abu Dhabi. An organization's personality is shaped by its common beliefs, goals, practices, or company culture. So, digging into the company culture reveals the core beliefs of the organization, its objectives, and its development team. 

Now, you might be wondering, how will you identify the company's culture? Well, you can take reference from the following sources – 

  • Social media posts 
  • App development process
  • About us Page
  • Client testimonials

#Step 2 - Refer to Clients' Reviews

Another best way to choose the On-demand app development firm for your restaurant business is to refer to the clients' reviews. Reviews are frequently available on the organization's website with a tag of "Reviews" or "Testimonials." It's important to read the reviews as they will help you determine how happy customers are with the company's app development process. 

You can also assess a company's abilities through reviews and customer testimonials. They can let you know if the mobile app developers create a valuable app or not. 

#Step 3 – Analyze the App Development Process

Regardless of the company's size or scope, adhering to the restaurant delivery app development process will ensure the success of your business application. Knowing the processes an app developer follows in designing and producing a top-notch app will help you know the working process. Organizations follow different app development approaches, so getting well-versed in the process is essential before finalizing any mobile app development company. 

#Step 4 – Consider Previous Experience

Besides considering other factors, considering the previous experience of the developers is a must. You can obtain a broad sense of the developer's capacity to assist you in creating a unique mobile application for a restaurant business.

You can also find out if the developers' have contributed to the creation of other successful applications or not. It will help you know the working capacity of a particular developer or organization. Prior experience is essential to evaluating their work. For instance, whether they haven't previously produced an app similar to yours or not. 

#Step 5 – Check for Their Technical Support

As you expect a working and successful restaurant mobile app for your business, checking on this factor is a must. A well-established organization is nothing without a good technical support team. So, ensure whatever restaurant mobile app development company you choose they must be well-equipped with a team of dedicated developers, designers, and testers. 

Strong tech support from your mobile app developers will help you identify new bugs and fix them bugs on time. All this will ensure the application's success. 

#Step 6 – Analyze Design Standards

Besides focusing on an organization's development, testing, and technical support, you should check the design standards. An appealing design is crucial in attracting new users and keeping the existing ones stick to your services. So, spend some time analyzing the design standards of an organization. Now, you might be wondering, how will you do it? Simple! By looking at the organization's portfolio. 

Whether hiring an iPhone app development company or any other, these steps apply to all. So, don't miss these steps. 

#Step 7 – Know Their Location

Finally, the last yet very crucial factor that will not only help you finalize the right person for your restaurant mobile app development but will also decide the mobile app development cost. So, you have to choose the location of the developers wisely, as it is a crucial factor in defining the cost. 

Summing Up!!!

Restaurant mobile applications have taken the food industry to heights none have ever considered. As a result, the demand for restaurant mobile app development companies has risen greatly, which is why businesses find it difficult to finalize the right person. But, we hope that after referring to this article, it will now be easier to hire dedicated developers under the desired budget. So, begin the hiring process now and get a well-craft food ordering app in hand. 

How much does it cost to build a video sharing app?

There are so many things you can do with your mobile phone, regardless of which operating system you use. Your smartphone is a miniature computer, which means you can use it to browse the web, stream music and download apps galore. You can also share videos with certain apps. There is no doubt that video, editing, recording, and sharing application development will give a wholesome solution to your app users and will help you make your application stand out from the competitors.

Are you searching for the app development company who build video sharing app? If yes then AppClues Infotech is the best mobile app development company offer world-class mobile app development services at competitive prices across all major mobile platforms for start-ups as well as enterprises. Our team of professional designers and developers can proficiently develop a video sharing mobile app tailored to your needs, to help you achieve the end result of your business gaining more market autonomy.

Our Expertise in Mobile App Development:

  • iPhone App Development
  • iPad App Development
  • Apple Watch App Development
  • Flutter App Development
  • Android App Development
  • Ionic App Development
  • React Native App Development
  • Windows App Development
  • Cross-Platform App Development

We offer custom social networking app development solutions which are designed to not just make your brand a household name but also to keep your brand above the ever-growing crowd of entertainment mobile apps. We build mobile apps across various industry verticals including travel, social networking, restaurant, real estate, health care, news, etc.

The expense of video sharing app development depends on app size, app platform, app functionality, what features you require, the team of app developers, etc. So generally cost is in between $2,000 - 15,000. It can vary from app to app because every app has different requirements.

#video sharing app development #best video sharing app development company #top video sharing app development company #make a video sharing mobile app #cost to create a video sharing app

Moli Ena

1583925761

Discord Screen Share and Video call: A Complete, 10-Step Guide

Originally Published at Troop Messenger

If you play PC games online, it’s safe to assume that you are familiar with Discord.

If not, this article can be a great resource because Discord has some of the best screen-sharing features, which can benefit both gamers and non-gamers.

You and up to 9 friends can simultaneously screen share on the discord server. At one time, 10 Discord users can conduct a live video chat, while they all are sharing their desktop screens, simultaneously.

Discord Screen Share feature has made Discord an incredibly powerful software for virtual collaboration, especially for teams that require online meetings and video calling from remote locations.

Discord has literally changed the way video conferences work. It’s peak concurrent users recently topped at 8.2 million.

Since Discord is spreading its wings as a real competitor of business communication and collaboration tools, we’ve got quite a few queries on ‘How to share screen on discord.’

In this article, we are going to show you 10 Easy-to-follow steps to configuring and using video calling and screen sharing feature of Discord:

What is Discord Application?
Discord is inarguably one of the most commonly used communication tools for online streaming and gaming.

Essentially, it’s a Skype Alternative for gamers, that is specifically designed to help the gamers coordinate and communicate through private servers which allow users to voice-chat and text with other people.

Discord application primarily functions with mobile and desktop platforms, and combines the features of:

A message board
A chat room
A VoIP chatting system

Discord’s popularity has increased over the past few years and the app has over 250 million registered users.

Discord Screen Share
One of the most powerful features of Discord is Screen Sharing, which was added in August 2017. The screen sharing feature allows users on the Discord chat server to view and interact with your screen.

Alongside the screen sharing, you can also conduct video calling, simultaneously, on the chat servers that is a great in-built feature of Discord. The users do not need to install another software, a discord screen share extension or integrate a third-party application

Screen Sharing & Video Camera Features: On Desktop

If you are using Discord on PC, you can avail the following features:

  1. Share Sound:
    While you are sharing your discord or computer screen on Discord Server, you can also opt-out of sound sharing. This feature helps a great deal when you’re in a public place, and you want to cut down on the background noise to avoid disturbance.

You can opt-in or opt-out of sound sharing by toggling the sound icon between Off and On.

  1. Swap from Screen Share to Video:
    An icon located at the bottom of the video screen enables Discord users to swap from a screen share to only video calling, and vice versa.

At anytime during the conversation, you can swap between the two. When swapping your computer screen, you can opt for which monitor screen to share. You can also opt for sharing only a specific application window.

  1. Video Marquee
    Discord Users who wish to see only a specific video and opt-out of seeing others can make use of the Video Marquee feature.

For this, you’d need to click on the user’s avatar, which will make the video to pop-out among others.

Screen Sharing & Video Camera Features: On Smartphone
If you are using Discord on your smartphone, you can avail the following features :

Unfortunately, the screen sharing feature is not available for Discord Smartphone users. So, you cannot avail of discord screen share for mobile.

Toggle Mute:

Should you wish to tune-out of the background or surrounding noise, the Toggle Mute feature can be a savior.

In the smartphone version of Discord, a user when on a video call, can mute their phone’s mic to prevent the outgoing sound on a chat server.

Tune Camera:

While making a video call through Discord mobile app, you can tune your camera, start and stop it from functioning at any time.

Similarly, there’s also an option to switch from front to back camera, and vice versa.

Audio Output (only for iOS):
This is an exclusive feature for Discord’s iPhone application. Audio Output is located on the top-right corner, next to the Switch Camera icon.

Using this, you can swap the audio output between your wireless headset or iPhone’s default speaker.

Step-by-Step Guide For Video Calling With Some Hacks
In this section, you’ll learn about the different ways to share your computer screen with another discord user.

To initiate video calling and screen sharing, install the Discord Application in your device, and configure video and audio hardware on Discord client.

a) Camera Settings

Step 1: Find the ‘Setting’ icon at the bottom left side of your screen, and click on the settings.

Step 2: To adjust your Video and Voice chat settings, look for the ‘Voice and Video’ Option under the ‘App Settings’ category on the left-hand menu.

Step 3: Should you wish to change the video settings, scroll down to find ‘Video Settings’ and opt for ‘Video Camera Hardware’. You can also do a test video.

b) Connecting with Users
Step 4: On the top-left panel, find Discord icon, and navigate to ‘Homepage.’ Click on the ‘Friends’ icon to open the list of friends on your discord server.

Step 5: Hover over the user’s name, and opt for Video calling.

Step 6: Click on the Video icon to enable a video conference with the user

Step-by-Step Guide For Discord Screen Sharing With Some Hacks
For discord screen share in the server, you’d need to initiate a Video call using the steps defined above.

Let’s proceed to Step 6 and see how you can enable screen sharing via Discord, and peek into your friend’s desktop.

Step 7: As the video calling is in process, look for a screen sharing icon present on the bottom of your screen. You can identify a screen-sharing icon that resembles a computer display with an arrow at the center.

Step 8: Click on this icon to enable screen sharing of your PC, and opt between sharing ‘Your Entire Screen’ or ‘Application Window.’

Step 9: You can further interchange share screen discord and video calling features by clicking on the same icon.

Step 10: To Stop sharing the screen, you can hover back to the ‘screen share’ icon and opt for ‘More Screen Share Options,’ and ‘Turn Off Screen Sharing.’

#discord video call

Dylan  Iqbal

Dylan Iqbal

1561523460

Matplotlib Cheat Sheet: Plotting in Python

This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.

Data visualization and storytelling with your data are essential skills that every data scientist needs to communicate insights gained from analyses effectively to any audience out there. 

For most beginners, the first package that they use to get in touch with data visualization and storytelling is, naturally, Matplotlib: it is a Python 2D plotting library that enables users to make publication-quality figures. But, what might be even more convincing is the fact that other packages, such as Pandas, intend to build more plotting integration with Matplotlib as time goes on.

However, what might slow down beginners is the fact that this package is pretty extensive. There is so much that you can do with it and it might be hard to still keep a structure when you're learning how to work with Matplotlib.   

DataCamp has created a Matplotlib cheat sheet for those who might already know how to use the package to their advantage to make beautiful plots in Python, but that still want to keep a one-page reference handy. Of course, for those who don't know how to work with Matplotlib, this might be the extra push be convinced and to finally get started with data visualization in Python. 

You'll see that this cheat sheet presents you with the six basic steps that you can go through to make beautiful plots. 

Check out the infographic by clicking on the button below:

Python Matplotlib cheat sheet

With this handy reference, you'll familiarize yourself in no time with the basics of Matplotlib: you'll learn how you can prepare your data, create a new plot, use some basic plotting routines to your advantage, add customizations to your plots, and save, show and close the plots that you make.

What might have looked difficult before will definitely be more clear once you start using this cheat sheet! Use it in combination with the Matplotlib Gallery, the documentation.

Matplotlib 

Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

Prepare the Data 

1D Data 

>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)

2D Data or Images 

>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = 1 X** 2 + Y
>>> V = 1 + X Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

Create Plot

>>> import matplotlib.pyplot as plt

Figure 

>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))

Axes 

>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) #row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)

Save Plot 

>>> plt.savefig('foo.png') #Save figures
>>> plt.savefig('foo.png',  transparent=True) #Save transparent figures

Show Plot

>>> plt.show()

Plotting Routines 

1D Data 

>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y values and 0

2D Data 

>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, #Colormapped or RGB arrays
      cmap= 'gist_earth', 
      interpolation= 'nearest',
      vmin=-2,
      vmax=2)
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour plot

Vector Fields 

>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows

Data Distributions 

>>> ax1.hist(y) #Plot a histogram
>>> ax3.boxplot(y) #Make a box and whisker plot
>>> ax3.violinplot(z)  #Make a violin plot

Plot Anatomy & Workflow 

Plot Anatomy 

 y-axis      

                           x-axis 

Workflow 

The basic steps to creating plots with matplotlib are:

1 Prepare Data
2 Create Plot
3 Plot
4 Customized Plot
5 Save Plot
6 Show Plot

>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]  #Step 1
>>> y = [10,20,25,30] 
>>> fig = plt.figure() #Step 2
>>> ax = fig.add_subplot(111) #Step 3
>>> ax.plot(x, y, color= 'lightblue', linewidth=3)  #Step 3, 4
>>> ax.scatter([2,4,6],
          [5,15,25],
          color= 'darkgreen',
          marker= '^' )
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png' ) #Step 5
>>> plt.show() #Step 6

Close and Clear 

>>> plt.cla()  #Clear an axis
>>> plt.clf(). #Clear the entire figure
>>> plt.close(). #Close a window

Plotting Customize Plot 

Colors, Color Bars & Color Maps 

>>> plt.plot(x, x, x, x**2, x, x** 3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c= 'k')
>>> fig.colorbar(im, orientation= 'horizontal')
>>> im = ax.imshow(img,
            cmap= 'seismic' )

Markers 

>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker= ".")
>>> ax.plot(x,y,marker= "o")

Linestyles 

>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls= 'solid') 
>>> plt.plot(x,y,ls= '--') 
>>> plt.plot(x,y,'--' ,x**2,y**2,'-.' ) 
>>> plt.setp(lines,color= 'r',linewidth=4.0)

Text & Annotations 

>>> ax.text(1,
           -2.1, 
           'Example Graph', 
            style= 'italic' )
>>> ax.annotate("Sine", 
xy=(8, 0),
xycoords= 'data', 
xytext=(10.5, 0),
textcoords= 'data', 
arrowprops=dict(arrowstyle= "->", 
connectionstyle="arc3"),)

Mathtext 

>>> plt.title(r '$sigma_i=15$', fontsize=20)

Limits, Legends and Layouts 

Limits & Autoscaling 

>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal')  #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])  #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) #Set limits for x-axis

Legends 

>>> ax.set(title= 'An Example Axes',  #Set a title and x-and y-axis labels
            ylabel= 'Y-Axis', 
            xlabel= 'X-Axis')
>>> ax.legend(loc= 'best')  #No overlapping plot elements

Ticks 

>>> ax.xaxis.set(ticks=range(1,5),  #Manually set x-ticks
             ticklabels=[3,100, 12,"foo" ])
>>> ax.tick_params(axis= 'y', #Make y-ticks longer and go in and out
             direction= 'inout', 
              length=10)

Subplot Spacing 

>>> fig3.subplots_adjust(wspace=0.5,   #Adjust the spacing between subplots
             hspace=0.3,
             left=0.125,
             right=0.9,
             top=0.9,
             bottom=0.1)
>>> fig.tight_layout() #Fit subplot(s) in to the figure area

Axis Spines 

>>> ax1.spines[ 'top'].set_visible(False) #Make the top axis line for a plot invisible
>>> ax1.spines['bottom' ].set_position(( 'outward',10))  #Move the bottom axis line outward

Have this Cheat Sheet at your fingertips

Original article source at https://www.datacamp.com

#matplotlib #cheatsheet #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