Search

Blog Archive

Monday, 20 August 2018

Variables and Scripts in Python

Variables and Scripts in Python
Variables and Scripts in Python

Variables

Also Read:PYTHON SCHOOL

 
Now let's start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables. Open up IDLE and click 'File > New Window'. A new window now appears, and it is easy to type in programs. Type the following (or just copy and paste—just read very carefully, and compare the code to the output that the program will make):
Code Example 3 – Variables
# Variables demonstrated
print ("This program is a demo of variables.")
v = 1
# Note: 'print ("value, v")' would be print out as "(value 1)", instead just do 'print "value, v"' to get "value 1" outputted.
print ("The value of v is now"), v
v = v + 1
print ("v now equals itself plus one, making it worth"), v
v = 51
print("v can store any numerical value, to be used elsewhere.")
print("For example, in a sentence. v is now worth"), v
print ("v times 5 equals"), v*5
print ("But v still only remains"), v
print("To make v five times bigger, you would have to type v = v*5")
v = v * 5
print ("There you go, now v equals", v, "and not"), v/5
Also Read:PYTHON SCHOOL

 
Note that if you just want to modify a variable's value with respect to itself, there are shortcuts. These are called augmented assignment operators:
Table 1 – Augmented operators
Standard formAugmented
v = v + 5v += 5
v = v - 5v -= 5
v = v*5v *= 5
v = v/5v /= 5

Strings

As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:
Code Example 4 – Strings
#Giving variables text, and adding text.
word1 = "Good"
word2 = "morning"
word3 = "to you too!"
print(word1, word2)
sentence = word1 + " " + word2 + " " + word3
print(sentence)
Also Read:PYTHON SCHOOL

 
The output will be:
Code Example 5 – String output
Good morning
Good morning to you too!
As you see, the variables above were holding text. Variable names can also be longer than one letter—here, we had word1, word2, and word3. As you can also see, strings can be added together to make longer words or sentences. However, spaces aren't added in between the words—hence me putting in the " " things (there is one space between those).

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. In code example 3:

    'print ("The value of v is now"), v' gives the output of:
    'The value of v is now'

    It doesn't show the value of v. Instead, you have to put the final parentheses after the variable 'v':
    >>>print("The value of v is now", v)
    'The value of v is now 255'

    The same for each line of code

    ReplyDelete