1593307500
In this Python video i want to show you How to Create Print Dialog in Pyside2, so for this purpose we are going to use QPrinter and QPrintDialog from QPrintSupport class. Pyside2 provides extensive cross-platform support for printing. Using the printing systems on each platform, Pyside2 applications can print to attached printers and across networks to remote printers. the print dialog allows users to change document-related settings, such as the paper size and orientation, type of print (color or grayscale), range of pages, and number of copies to print. controls are also provided to enable users to choose from the printers available, including any configured network printers. typically, QPrintDialog objects are constructed with a QPrinter object, and executed using the exec() function.
#python #pyside2
1669003576
In this Python article, let's learn about Mutable and Immutable in Python.
Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn’t allow any change in the object once it has been created.
Both of these states are integral to Python data structure. If you want to become more knowledgeable in the entire Python Data Structure, take this free course which covers multiple data structures in Python including tuple data structure which is immutable. You will also receive a certificate on completion which is sure to add value to your portfolio.
Mutable is when something is changeable or has the ability to change. In Python, ‘mutable’ is the ability of objects to change their values. These are often the objects that store a collection of data.
Immutable is the when no change is possible over time. In Python, if the value of an object cannot be changed over time, then it is known as immutable. Once created, the value of these objects is permanent.
Objects of built-in type that are mutable are:
Objects of built-in type that are immutable are:
Object mutability is one of the characteristics that makes Python a dynamically typed language. Though Mutable and Immutable in Python is a very basic concept, it can at times be a little confusing due to the intransitive nature of immutability.
In Python, everything is treated as an object. Every object has these three attributes:
While ID and Type cannot be changed once it’s created, values can be changed for Mutable objects.
Check out this free python certificate course to get started with Python.
I believe, rather than diving deep into the theory aspects of mutable and immutable in Python, a simple code would be the best way to depict what it means in Python. Hence, let us discuss the below code step-by-step:
#Creating a list which contains name of Indian cities
cities = [‘Delhi’, ‘Mumbai’, ‘Kolkata’]
# Printing the elements from the list cities, separated by a comma & space
for city in cities:
print(city, end=’, ’)
Output [1]: Delhi, Mumbai, Kolkata
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(cities)))
Output [2]: 0x1691d7de8c8
#Adding a new city to the list cities
cities.append(‘Chennai’)
#Printing the elements from the list cities, separated by a comma & space
for city in cities:
print(city, end=’, ’)
Output [3]: Delhi, Mumbai, Kolkata, Chennai
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(cities)))
Output [4]: 0x1691d7de8c8
The above example shows us that we were able to change the internal state of the object ‘cities’ by adding one more city ‘Chennai’ to it, yet, the memory address of the object did not change. This confirms that we did not create a new object, rather, the same object was changed or mutated. Hence, we can say that the object which is a type of list with reference variable name ‘cities’ is a MUTABLE OBJECT.
Let us now discuss the term IMMUTABLE. Considering that we understood what mutable stands for, it is obvious that the definition of immutable will have ‘NOT’ included in it. Here is the simplest definition of immutable– An object whose internal state can NOT be changed is IMMUTABLE.
Again, if you try and concentrate on different error messages, you have encountered, thrown by the respective IDE; you use you would be able to identify the immutable objects in Python. For instance, consider the below code & associated error message with it, while trying to change the value of a Tuple at index 0.
#Creating a Tuple with variable name ‘foo’
foo = (1, 2)
#Changing the index[0] value from 1 to 3
foo[0] = 3
TypeError: 'tuple' object does not support item assignment
Once again, a simple code would be the best way to depict what immutable stands for. Hence, let us discuss the below code step-by-step:
#Creating a Tuple which contains English name of weekdays
weekdays = ‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’
# Printing the elements of tuple weekdays
print(weekdays)
Output [1]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’)
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(weekdays)))
Output [2]: 0x1691cc35090
#tuples are immutable, so you cannot add new elements, hence, using merge of tuples with the # + operator to add a new imaginary day in the tuple ‘weekdays’
weekdays += ‘Pythonday’,
#Printing the elements of tuple weekdays
print(weekdays)
Output [3]: (‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’, ‘Pythonday’)
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(weekdays)))
Output [4]: 0x1691cc8ad68
This above example shows that we were able to use the same variable name that is referencing an object which is a type of tuple with seven elements in it. However, the ID or the memory location of the old & new tuple is not the same. We were not able to change the internal state of the object ‘weekdays’. The Python program manager created a new object in the memory address and the variable name ‘weekdays’ started referencing the new object with eight elements in it. Hence, we can say that the object which is a type of tuple with reference variable name ‘weekdays’ is an IMMUTABLE OBJECT.
Also Read: Understanding the Exploratory Data Analysis (EDA) in Python
Where can you use mutable and immutable objects:
Mutable objects can be used where you want to allow for any updates. For example, you have a list of employee names in your organizations, and that needs to be updated every time a new member is hired. You can create a mutable list, and it can be updated easily.
Immutability offers a lot of useful applications to different sensitive tasks we do in a network centred environment where we allow for parallel processing. By creating immutable objects, you seal the values and ensure that no threads can invoke overwrite/update to your data. This is also useful in situations where you would like to write a piece of code that cannot be modified. For example, a debug code that attempts to find the value of an immutable object.
Watch outs: Non transitive nature of Immutability:
OK! Now we do understand what mutable & immutable objects in Python are. Let’s go ahead and discuss the combination of these two and explore the possibilities. Let’s discuss, as to how will it behave if you have an immutable object which contains the mutable object(s)? Or vice versa? Let us again use a code to understand this behaviour–
#creating a tuple (immutable object) which contains 2 lists(mutable) as it’s elements
#The elements (lists) contains the name, age & gender
person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])
#printing the tuple
print(person)
Output [1]: (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female'])
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(person)))
Output [2]: 0x1691ef47f88
#Changing the age for the 1st element. Selecting 1st element of tuple by using indexing [0] then 2nd element of the list by using indexing [1] and assigning a new value for age as 4
person[0][1] = 4
#printing the updated tuple
print(person)
Output [3]: (['Ayaan', 4, 'Male'], ['Aaradhya', 8, 'Female'])
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(person)))
Output [4]: 0x1691ef47f88
In the above code, you can see that the object ‘person’ is immutable since it is a type of tuple. However, it has two lists as it’s elements, and we can change the state of lists (lists being mutable). So, here we did not change the object reference inside the Tuple, but the referenced object was mutated.
Also Read: Real-Time Object Detection Using TensorFlow
Same way, let’s explore how it will behave if you have a mutable object which contains an immutable object? Let us again use a code to understand the behaviour–
#creating a list (mutable object) which contains tuples(immutable) as it’s elements
list1 = [(1, 2, 3), (4, 5, 6)]
#printing the list
print(list1)
Output [1]: [(1, 2, 3), (4, 5, 6)]
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(list1)))
Output [2]: 0x1691d5b13c8
#changing object reference at index 0
list1[0] = (7, 8, 9)
#printing the list
Output [3]: [(7, 8, 9), (4, 5, 6)]
#printing the location of the object created in the memory address in hexadecimal format
print(hex(id(list1)))
Output [4]: 0x1691d5b13c8
As an individual, it completely depends upon you and your requirements as to what kind of data structure you would like to create with a combination of mutable & immutable objects. I hope that this information will help you while deciding the type of object you would like to select going forward.
Before I end our discussion on IMMUTABILITY, allow me to use the word ‘CAVITE’ when we discuss the String and Integers. There is an exception, and you may see some surprising results while checking the truthiness for immutability. For instance:
#creating an object of integer type with value 10 and reference variable name ‘x’
x = 10
#printing the value of ‘x’
print(x)
Output [1]: 10
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(x)))
Output [2]: 0x538fb560
#creating an object of integer type with value 10 and reference variable name ‘y’
y = 10
#printing the value of ‘y’
print(y)
Output [3]: 10
#Printing the location of the object created in the memory address in hexadecimal format
print(hex(id(y)))
Output [4]: 0x538fb560
As per our discussion and understanding, so far, the memory address for x & y should have been different, since, 10 is an instance of Integer class which is immutable. However, as shown in the above code, it has the same memory address. This is not something that we expected. It seems that what we have understood and discussed, has an exception as well.
Quick check – Python Data Structures
Tuples are immutable and hence cannot have any changes in them once they are created in Python. This is because they support the same sequence operations as strings. We all know that strings are immutable. The index operator will select an element from a tuple just like in a string. Hence, they are immutable.
Like all, there are exceptions in the immutability in python too. Not all immutable objects are really mutable. This will lead to a lot of doubts in your mind. Let us just take an example to understand this.
Consider a tuple ‘tup’.
Now, if we consider tuple tup = (‘GreatLearning’,[4,3,1,2]) ;
We see that the tuple has elements of different data types. The first element here is a string which as we all know is immutable in nature. The second element is a list which we all know is mutable. Now, we all know that the tuple itself is an immutable data type. It cannot change its contents. But, the list inside it can change its contents. So, the value of the Immutable objects cannot be changed but its constituent objects can. change its value.
Mutable Object | Immutable Object |
State of the object can be modified after it is created. | State of the object can’t be modified once it is created. |
They are not thread safe. | They are thread safe |
Mutable classes are not final. | It is important to make the class final before creating an immutable object. |
list, dictionary, set, user-defined classes.
int, float, decimal, bool, string, tuple, range.
Lists in Python are mutable data types as the elements of the list can be modified, individual elements can be replaced, and the order of elements can be changed even after the list has been created.
(Examples related to lists have been discussed earlier in this blog.)
Tuple and list data structures are very similar, but one big difference between the data types is that lists are mutable, whereas tuples are immutable. The reason for the tuple’s immutability is that once the elements are added to the tuple and the tuple has been created; it remains unchanged.
A programmer would always prefer building a code that can be reused instead of making the whole data object again. Still, even though tuples are immutable, like lists, they can contain any Python object, including mutable objects.
A set is an iterable unordered collection of data type which can be used to perform mathematical operations (like union, intersection, difference etc.). Every element in a set is unique and immutable, i.e. no duplicate values should be there, and the values can’t be changed. However, we can add or remove items from the set as the set itself is mutable.
Strings are not mutable in Python. Strings are a immutable data types which means that its value cannot be updated.
Join Great Learning Academy’s free online courses and upgrade your skills today.
Original article source at: https://www.mygreatlearning.com
1672928580
Bash has no built-in function to take the user’s input from the terminal. The read command of Bash is used to take the user’s input from the terminal. This command has different options to take an input from the user in different ways. Multiple inputs can be taken using the single read command. Different ways of using this command in the Bash script are described in this tutorial.
read [options] [var1, var2, var3…]
The read command can be used without any argument or option. Many types of options can be used with this command to take the input of the particular data type. It can take more input from the user by defining the multiple variables with this command.
Some options of the read command require an additional parameter to use. The most commonly used options of the read command are mentioned in the following:
Option | Purpose |
---|---|
-d <delimiter> | It is used to take the input until the delimiter value is provided. |
-n <number> | It is used to take the input of a particular number of characters from the terminal and stop taking the input earlier based on the delimiter. |
-N <number> | It is used to take the input of the particular number of characters from the terminal, ignoring the delimiter. |
-p <prompt> | It is used to print the output of the prompt message before taking the input. |
-s | It is used to take the input without an echo. This option is mainly used to take the input for the password input. |
-a | It is used to take the input for the indexed array. |
-t <time> | It is used to set a time limit for taking the input. |
-u <file descriptor> | It is used to take the input from the file. |
-r | It is used to disable the backslashes. |
The uses of read command with different options are shown in this part of this tutorial.
Example 1: Using Read Command without Any Option and variable
Create a Bash file with the following script that takes the input from the terminal using the read command without any option and variable. If no variable is used with the read command, the input value is stored in the $REPLY variable. The value of this variable is printed later after taking the input.
#!/bin/bash
#Print the prompt message
echo "Enter your favorite color: "
#Take the input
read
#Print the input value
echo "Your favorite color is $REPLY"
Output:
The following output appears if the “Blue” value is taken as an input:
Example 2: Using Read Command with a Variable
Create a Bash file with the following script that takes the input from the terminal using the read command with a variable. The method of taking the single or multiple variables using a read command is shown in this example. The values of all variables are printed later.
#!/bin/bash
#Print the prompt message
echo "Enter the product name: "
#Take the input with a single variable
read item
#Print the prompt message
echo "Enter the color variations of the product: "
#Take three input values in three variables
read color1 color2 color3
#Print the input value
echo "The product name is $item."
#Print the input values
echo "Available colors are $color1, $color2, and $color3."
Output:
The following output appears after taking a single input first and three inputs later:
Example 3: Using Read Command with -p Option
Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -p option. The input value is printed later.
#!/bin/bash
#Take the input with the prompt message
read -p "Enter the book name: " book
#Print the input value
echo "Book name: $book"
Output:
The following output appears after taking the input:
Example 4: Using Read Command with -s Option
Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -s option. The input value of the password will not be displayed for the -s option. The input values are checked later for authentication. A success or failure message is also printed.
#!/bin/bash
#Take the input with the prompt message
read -p "Enter your email: " email
#Take the secret input with the prompt message
read -sp "Enter your password: " password
#Add newline
echo ""
#Check the email and password for authentication
if [[ $email == "admin@example.com" && $password == "secret" ]]
then
#Print the success message
echo "Authenticated."
else
#Print the failure message
echo "Not authenticated."
fi
Output:
The following output appears after taking the valid and invalid input values:
Example 5: Using Read Command with -a Option
Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -a option. The array values are printed later after taking the input values from the terminal.
#!/bin/bash
echo "Enter the country names: "
#Take multiple inputs using an array
read -a countries
echo "Country names are:"
#Read the array values
for country in ${countries[@]}
do
echo $country
done
Output:
The following output appears after taking the array values:
Example 6: Using Read Command with -n Option
Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -n option.
#!/bin/bash
#Print the prompt message
echo "Enter the product code: "
#Take the input of five characters
read -n 5 code
#Add newline
echo ""
#Print the input value
echo "The product code is $code"
Output:
The following output appears if the “78342” value is taken as input:
Example 7: Using Read Command with -t Option
Create a Bash file with the following script that takes the input from the terminal using the read command with a variable and the -t option.
#!/bin/bash
#Print the prompt message
echo -n "Write the result of 10-6: "
#Take the input of five characters
read -t 3 answer
#Check the input value
if [[ $answer == "4" ]]
then
echo "Correct answer."
else
echo "Incorrect answer."
fi
Output:
The following output appears after taking the correct and incorrect input values:
The uses of some useful options of the read command are explained in this tutorial using multiple examples to know the basic uses of the read command.
Original article source at: https://linuxhint.com/
1655630160
Install via pip:
$ pip install pytumblr
Install from source:
$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install
A pytumblr.TumblrRestClient
is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:
client = pytumblr.TumblrRestClient(
'<consumer_key>',
'<consumer_secret>',
'<oauth_token>',
'<oauth_secret>',
)
client.info() # Grabs the current user information
Two easy ways to get your credentials to are:
interactive_console.py
tool (if you already have a consumer key & secret)client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user
client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog
client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post
client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog
Creating posts
PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.
The default supported types are described below.
We'll show examples throughout of these default examples while showcasing all the specific post types.
Creating a photo post
Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload
#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],
source="https://68.media.tumblr.com/b965fbb2e501610a29d80ffb6fb3e1ad/tumblr_n55vdeTse11rn1906o1_500.jpg")
#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
tweet="Woah this is an incredible sweet post [URL]",
data="/Users/johnb/path/to/my/image.jpg")
#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
caption="## Mega sweet kittens")
Creating a text post
Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html
#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")
Creating a quote post
Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported
#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")
Creating a link post
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
description="Search is pretty cool when a duck does it.")
Creating a chat post
Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)
#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
"""
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])
Creating an audio post
Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr
#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")
#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")
Creating a video post
Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload
#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",
embed="http://www.youtube.com/watch?v=40pUYLacrj4")
#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")
Editing a post
Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.
client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")
Reblogging a Post
Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.
client.reblog(blogName, id=125356, reblog_key="reblog_key")
Deleting a post
Deleting just requires that you own the post and have the post id
client.delete_post(blogName, 123456) # Deletes your post :(
A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):
client.create_text(blogName, tags=['hello', 'world'], ...)
Getting notes for a post
In order to get the notes for a post, you need to have the post id and the blog that it is on.
data = client.notes(blogName, id='123456')
The results include a timestamp you can use to make future calls.
data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])
# get posts with a given tag
client.tagged(tag, **params)
This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).
You'll need pyyaml
installed to run it, but then it's just:
$ python interactive-console.py
and away you go! Tokens are stored in ~/.tumblr
and are also shared by other Tumblr API clients like the Ruby client.
The tests (and coverage reports) are run with nose, like this:
python setup.py test
Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license
1652496780
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.
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
.
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:
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.
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.
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.
global
Keyword in PythonWhat 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
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/
1652450400
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 global
palabra clave.
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 int
tipo, 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 28
a 29
.
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 :
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.
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 NameError
porque no es 'visible' en el resto del programa. Solo es 'visible' dentro de la función donde se definió.
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 city
cambiarí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.
global
palabra 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 global
palabra 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 global
palabra 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 global
palabra 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
¡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/