Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Variables, Expression and Statements

Variables, Expression and Statements

Variables

  • A variable holds a value that may change.
  • Variables are containers for storing data values
  • Python has no command for declaring a variable
  • A variable is created the moment when the value is assigned to it

Initializing Variable,

vname = expression
= sign is known as assignment operator 
An expression is any value, text or arithmetic expression  
vname is the name of the variable 
The value of the expression is stored in the variable
>>> x = 1
>>> y = "ABC"
>>> z = 9.83
>>> x
1
>>> y
'ABC'
>>> z
9.83

Variables do not need to be declared with any particular type and can even change after they have been set

>>> x = 23
>>> x = "python"
>>> x
'python'
  • Variable Names
    • A variable can have a short name (Ex: x and y) or a more descriptive name (Ex: age, total, avg, grade)
    • Rules for naming a variable
      • A variable name must start with a letter or the underscore character
      • Example:
        • myname
        • _myname
      • A variable name cannot start with a number
        • Example: 2myname is illegal
        • Whereas myname2 is legal
      • A variable name can only contain alpha numeric characters and underscores ( A-z, 0-9 and _)
        • Example: Myname12_ is legal variable name
        • Whereas Myname@ is illegal
      • Variable names are case-sensitive
        • Example: subname, SubName, SUBNAME are three different variables
      • Reserved keywords should not be used as a variable name
        • Example: for, if, while

Expressions

  • An expression is combination of variables, operators, and values
  • An expression is a piece of code that has a value
  • It is even smaller and more fundamental than a statement
  • Usually right hand side of an assignment operator is termed as expression

Example:

>>> 1+3j
(1+3j)
>>> 2
2
>>> 5.3
5.3
>>> "python"
'python'

Statements

  • A statement is an instruction that the python interpreter can execute
  • A statement is a smallest piece of code that can be executed on its own
  • A statement is interpreted by the interpreter and after execution displays some result
  • A program can contain many statements in sequence
  • If there are multiple statements, the result is displayed after every statement

Example:

  • Print statement produces some result to display but it does not happen in case of assignment statement
  • Assignment statement
>>> x=2
>>> print(x)
2

Difference between Expression and Statement

Loading

Views: 9

Articles

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments