Variables

In this section, you will learn:

  • Create your own variables to store numbers, string and lists

  • Discuss the differences between different number types in Python

  • Use basic mathematical operations in Python to perform calculations

  • Explain the differences between strings, numbers and lists

  • Write out shorts programs in steps as comments to help you build your own code

  • Take user input in a variety of situations and use that input in your programs

Variables

Variables are where we keep our stuff in a program. A variable is something you want the computer to remember.

Python can remember several different types of values, including:

  • Numbers: 7, 42, 98.6

  • Strings: "letters", "words", "sentences"

x = 6
myName = "bob"
x = x + 1

The = sign is known as the assignment operator

Rules for Naming Variable

  1. Variable names in Python should begin with a letter (a-z)

  2. The rest of the name can include letters, numbers or the underscore symbol (_)

  3. Variable name are case sensitive: my_name, My_Name, and MY_NAME are all different variable names in Python

Strings

Strings are words and sentences in a program. To use strings in Python we surround our text with quotation marks.

Thankyou.py

Here we will store some information in variable and collect some information from the user before displaying it back on sentences.

Open a new file in the Python Idle and save it as Thankyou.py. Write out the following code:

Notice a few things:

  • At the end of the input text, there is a space. This prevents the answer from appears right up against the ?

  • We combine strings in the bring statement by separating out our strings and variables with a comma

Numbers

  • Integers - whole numbers including negatives like 7, -9, 9

  • Floating-point numbers - numbers with decimals like 1.0, 2.5, 3.14159265

Two do basic mathematical operations in Python, we use the Python arithmetic operators

We can also store values in variable in the Python shell.

Example: Python Does Your Maths Prep

We can use the eval() function to calculate basic maths problems in our program.

We have something new here. The While Loop. This will keep going until so long as the condition in the bracket is met. In this case, as long as the user input is not equal to q.

Lets go back to thankyou.py

We're going to add an extra print command that tells the user the difference between your age and Brysons. The problem is that Python doesn't know whether or not the input into your_age is a string or a number. We can tell Python that it is a number by using the eval() function. This is short for evaluate.

Change line 5 to:

Now Python knows that your_age is a number

Now create a new variable at the bottom of the file that works out the age difference and print it out

Project

Last updated

Was this helpful?