Python Variables – Shishir Kant Singh https://shishirkant.com Jada Sir जाड़ा सर :) Fri, 15 May 2020 11:56:05 +0000 en-US hourly 1 https://wordpress.org/?v=6.9 https://shishirkant.com/wp-content/uploads/2020/05/cropped-shishir-32x32.jpg Python Variables – Shishir Kant Singh https://shishirkant.com 32 32 187312365 Python Variables and Scope https://shishirkant.com/python-variables-and-scope/?utm_source=rss&utm_medium=rss&utm_campaign=python-variables-and-scope Fri, 15 May 2020 11:30:47 +0000 http://shishirkant.com/?p=230 What are Python Variables?

A variable is a container for a value. It can be assigned a name, you can use it to refer to it later in the program. Based on the value assigned, the interpreter decides its data type. You can always store a different type in a variable.

For example, if you store 7 in a variable, later, you can store ‘Shishir Kant’.

Python Variables Naming Rules

There are certain rules to what you can name a variable(called an identifier).

  • Python variables can only begin with a letter(A-Z/a-z) or an underscore(_).
>>> 9lives=9

SyntaxError: invalid syntax

>>> flag=0
>>> flag
>>> _9lives='kanpur'
>>> _9lives

‘kanpur’

  • The rest of the identifier may contain letters(A-Z/a-z), underscores(_), and numbers(0-9).
>>> year2='ShishirKant'
>>> year2

‘ShishirKant’

>>> _$$=7

SyntaxError: invalid syntax

  • Python is case-sensitive, and so are Python identifiers. Name and name are two different identifiers.
>>> name='SEED Group'
>>> name

‘SEED Group’

>>> Name

Traceback (most recent call last):
File “<pyshell#21>”, line 1, in <module>
Name
NameError: name ‘Name’ is not defined

  • Reserved words (keywords) cannot be used as identifier names.
anddefFalseimportnotTrue
asdelfinallyinortry
assertelifforispasswhile
breakelsefromlambdaprintwith
classexceptglobalNoneraiseyield
continueexecifnonlocalreturn

Assigning and Reassigning Python Variables

To assign a value to Python variables, you don’t need to declare its type. You name it according to the rules stated in section 2a, and type the value after the equal sign(=).

>>> age=7
>>> print(age)

7

>>> age='Shishir'
>>> print(age)

Shishir

However, age=Dinosaur doesn’t make sense. Also, you cannot use Python variables before assigning it a value.

>>> name

Traceback (most recent call last):
File “<pyshell#8>”, line 1, in <module>
name
NameError: name ‘name’ is not defined

You can’t put the identifier on the right-hand side of the equal sign, though. The following code causes an error.

>>> 7=age

SyntaxError: can’t assign to literal

Neither can you assign Python variables to a keyword.

>>> False=choice

SyntaxError: can’t assign to keyword

3. Multiple Assignment

You can assign values to multiple Python variables in one statement.

>>> age,city=21,'Lucknow'
>>> print(age,city)

21 Lucknow

Or you can assign the same value to multiple Python variables.

>>> age=fav=7
>>> print(age,fav)

7 7

This is how you assign values to Python Variables

4. Swapping Variables

Swapping means interchanging values. To swap Python variables, you don’t need to do much.

>>> a,b='red','blue'
>>> a,b=b,a
>>> print(a,b)

blue red

5. Deleting Variables

You can also delete Python variables using the keyword ‘del’.

>>> a='red'
>>> del a
>>> a

Traceback (most recent call last):
File “<pyshell#39>”, line 1, in <module>
a
NameError: name ‘a’ is not defined

This is How you can delete Python Variables

======================================================

Python Variable Scope

The scope of a variable in python is that part of the code where it is visible. Actually, to refer to it, you don’t need to use any prefixes then. Let’s take an example

>>> b=8
>>> def func():
               a=7
               print(a)
               print(b)
>>> func()

7
8

>>> a

Traceback (most recent call last):

File “<pyshell#6>”, line 1, in <module>

a

NameError: name ‘a’ is not defined
Also, the duration for which a variable is alive is called its ‘lifetime’.

Types of Python Variable Scope

There are 4 types of Variable Scope in Python, let’s discuss them one by one:

a. Local Scope

In the above code, we define a variable ‘a’ in a function ‘func’. So, ‘a’ is local to ‘func’. Hence, we can read/write it in func, but not outside it. When we try to do so, it raises a NameError.
Look at this code.

>>> a=0
>>> def func():
               print(a)
               a=1
               print(a)
>>> func()

Traceback (most recent call last):

File “<pyshell#79>”, line 1, in <module>

func()

File “<pyshell#78>”, line 2, in func

print(a)

UnboundLocalError: local variable ‘a’ referenced before assignment
Here, we could’ve accessed the global Scope ‘a’ inside ‘func’, but since we also define a local ‘a’ in it, it no longer accesses the global ‘a’. Then, the first print statement inside ‘func’ throws an error in Python, because we’re trying to access the local scope ‘a’ before assigning it. However, it is bad practice to try to manipulate global values from inside local scopes. Try to pass it as a parameter to the function.

>>> def func(a=0):
                  a+=1
                  print(a)
>>> func()

b. Global Scope

We also declare a variable ‘b’ outside any other python Variable scope, this makes it global scope. Consequently, we can read it anywhere in the program. Later in this article, we will see how to write it inside func.

c. Enclosing Scope

Let’s take another example.

>>> def red():
              a=1
              def blue():
                         b=2
                         print(a)
                         print(b)
              blue()
              print(a)
>>> red()

1
2
1
In this code, ‘b’ has local scope in Python function ‘blue’, and ‘a’ has nonlocal scope in ‘blue’. Of course, a python variable scope that isn’t global or local is nonlocal. This is also called enclosing scope.

d. Built-in Scope

Finally, we talk about the widest scope. The built-in scope has all the names that are loaded into python variable scope when we start the interpreter. For example, we never need to import any module to access functions like print() and id().
Now that we’ve discussed different types of python variable scopes, let’s see how to deal with them.

Global Keyword in Python

So far, we haven’t had any kind of a problem with global scope. So let’s take an example.

>>> a=1
>>> def counter():
                  a=2
                  print(a)
>>> counter()

2
Now, when we make a reference to ‘a’ outside this function, we get 1 instead of 2.

>>> a

1
Why does this happen? Well, this is because when we set ‘a’ to 2, it created a local variable ‘a’ in the local scope of ‘counter’. This didn’t change anything for the global ‘a’. Now, what if you wanted to change the global version of ‘a’? We use the ‘global’ keyword in python for this.

>>> a=1
>>> def counter():
                  global a
                  a=2
                  print(a)
>>> counter()

2

>>> a

2
What we do here is, we declare that the ‘a’ we’re going to use in this function is from the global scope. After this, whenever we make a reference to ‘a’ inside ‘counter’, the interpreter knows we’re talking about the global ‘a’. In this example, it changed the value of the global ‘a’ to 2.

Nonlocal Keyword

Like the ‘global’ keyword, you want to make a change to a nonlocal variable, you must use the ‘nonlocal’ keyword. Let’s first try this without the keyword.

>>> def red():
              a=1
              def blue():
                         a=2
                         b=2
                         print(a)
                         print(b)
              blue()
              print(a)
>>> red()

2
2
1
As you can see, this did not change the value of ‘a’ outside function ‘blue’. To be able to do that, we use ‘nonlocal’.

>>> def red():
              a=1
              def blue():
                         nonlocal a
                         a=2
                         b=2
                         print(a)
                         print(b)
              blue()
              print(a)
>>> red()

2
2
2

]]>
230
Python Syntax https://shishirkant.com/python-syntax/?utm_source=rss&utm_medium=rss&utm_campaign=python-syntax Fri, 15 May 2020 11:14:29 +0000 http://shishirkant.com/?p=227 What is Python Syntax?

The term syntax is referred to a set of rules and principles that describes the structure of a language. The Python syntax defines all the set of rules that are used to create sentences in Python programming. For example –  we have to learn grammar when we want to learn the English language. In the same way, you will need to learn and understand the Python syntax in order to learn the Python language.

Example of Python Syntax

Python is a popular language because of its elegant syntax structure. Let’s take a quick look at a simple Python program and you will get an idea of how programming in Python looks like.

print("Enter your name:")
name = input()
#getting user’s age
print("Enter your age:")
age = int(input())
#condition to check if user is eligible or not
if( age >= 18 ):
  print( name, ' is eligible to vote.')
else:
  print( name, ' is not eligible to vote.')

Output:

Enter your name:
Shishir
Enter your age:
19
Harsh is eligible to vote.

Types of Syntax Structures in Python

Python Line Structure

A Python program comprises logical lines. A NEWLINE token follows each of those. The interpreter ignores blank lines.

The following line causes an error.

>>>print("Hi
How are you?")

Output:

SyntaxError: EOL while scanning string literal

Python Multiline Statements

This one is an important Python syntax. We saw that Python does not mandate semicolons. A new line means a new statement. But sometimes, you may want to split a statement over two or more lines. It may be to aid readability. You can do so in the following ways.

2.1. Use a backward slash

>>> print("Hi\
how are you?")

Output:

Hihow are you?

You can also use it to distribute a statement without a string across lines.

>>> a\
=\
10
>>> print(a)

Output:

10

2.2. Put the String in Triple Quotes

>>> print("""Hi
        how are you?""")

Output:

Hi
how are you?

However, you can’t use backslashes inside a docstring for statements that aren’t a string.

>>> """b\
=\
10"""

Output:

‘b=10’

>>> print(b)

Output:

Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
print(b)
NameError: name ‘b’ is not defined

Python Comments

Python Syntax ‘Comments’ let you store tags at the right places in the code. You can use them to explain complex sections of code. The interpreter ignores comments. Declare a comment using an octothorpe (#).

>>> #This is a comment

Python does not support general multiline comments like Java or C++.

4. Python Docstrings

A docstring is a documentation string. As a comment, this Python Syntax is used to explain code. But unlike comments, they are more specific. Also, they are retained at runtime. This way, the programmer can inspect them at runtime. Delimit a docstring using three double-quotes. You may put it as a function’s first line to describe it.

>>> def func():
"""
This function prints out a greeting
"""
print("Hi")
>>> func()

Output:

Hi

Any queries yet in Python Syntax Tutorial? If yes, mention in the comment section. DataFlair’s team is here to help you.

5. Python Indentation

Since Python doesn’t use curly braces to delimit blocks of code, this Python Syntax is mandatory. You can indent code under a function, loop, or class.

>>> if 2>1:
print("2 is the bigger person");
print("But 1 is worthy too");

Output:

2 is the bigger person
But 1 is worthy too

You can indent using a number of tabs or spaces, or a combination of those. But remember, indent statements under one block of code with the same amount of tabs and spaces.

>>> if 2>1:
print("2 is the bigger person");
print("But 1 is worthy too");

Output:

SyntaxError: unindent does not match any outer indentation level

6. Python Multiple Statements in One Line

You can also fit in more than one statement on one line. Do this by separating them with a semicolon. But you’d only want to do so if it supplements readability.

>>> a=7;print(a);

Output:

7

7. Python Quotations

Python supports the single quote and the double quote for string literals. But if you begin a string with a single quote, you must end it with a single quote. The same goes for double-quotes.

The following string is delimited by single quotes.

>>> print('We need a chaperone');

Output:

We need a chaperone

This string is delimited by double-quotes.

>>> print("We need a 'chaperone'");

Output:

We need a ‘chaperone’

Notice how we used single quotes around the word chaperone in the string? If we used double quotes everywhere, the string would terminate prematurely.

>>> print("We need a "chaperone"");

Output:

SyntaxError: invalid syntax

8. Python Blank Lines

If you leave a line with just whitespace, the interpreter will ignore it.

9. Python Identifiers

An identifier is a name of a program element, and it is user-defined. This Python Syntax uniquely identifies the element. There are some rules to follow while choosing an identifier:

  1. An identifier may only begin with A-Z, a-z, or an underscore(_).
  2. This may be followed by letters, digits, and underscores- zero or more.
  3. Python is case-sensitive. Name and name are two different identifiers.
  4. A reserved keyword may not be used as an identifier. The following is a list of keywords.
anddefFalseimportnotTrue
asdelfinallyinortry
assertelifforispasswhile
breakelsefromlambdaprintwith
classexceptglobalNoneraiseyield
continueexecifnonlocalreturn

Apart from these rules, there are a few naming conventions that you should follow while using this Python syntax:

  1. Use uppercase initials for class names, lowercase for all others.
  2. Name a private identifier with a leading underscore ( _username)
  3. Name a strongly private identifier with two leading underscores ( __password)
  4. Special identifiers by Python end with two leading underscores.

10. Python Variables

In Python, you don’t define the type of the variable. It is assumed on the basis of the value it holds.

>>> x=10
>>> print(x)

Output:

10

>>> x='Hello'
>>> print(x)

Output:

Hello

Here, we declared a variable x and assigned it a value of 10. Then we printed its value. Next, we assigned it the value ‘Hello’ and printed it out. So, we see, a variable can hold any type of value at a later instant. Hence, Python is a dynamically-typed language.

11. Python String Formatters

Now let us see the different types of String formatters in Python:

11.1. % Operator

You can use the % operator to format a string to contain text as well as values of identifiers. Use %s where you want a value to appear. After the string, put a % operator and mention the identifiers in parameters.

>>> x=10; printer="HP"
>>> print("I just printed %s pages to the printer %s" % (x, printer))

Output:

I just printed 10 pages to the printer HP

11.2. Format Method

The format method allows you to format a string in a similar way. At the places, you want to put values, put 0,1,2,.. in curly braces. Call the format method on the string and mention the identifiers in the parameters.

>>> print("I just printed {0} pages to the printer {1}".format(x, printer))

Output:

I just printed 10 pages to the printer HP

You can also use the method to print out identifiers that match certain values.

>>> print("I just printed {x} pages to the printer {printer}".format(x=7, printer='HP'))

Output:

I just printed 7 pages to the printer HP

11.3. f-strings

If you use an f-string, you just need to mention the identifiers in curly braces. Also, write ‘f’ right before the string, but outside the quotes used.

>>> print(f"I just printed {x} pages to the printer {printer}")

Output:

I just printed 10 pages to the printer HP

]]>
227