1. Variables: What They Look Like
Go to Chapter 2 of A Smarter Way.
Variable names can contain letters, numbers and underscores – nothing else.
And variable names must always begin with a letter or underscore, but never a number.
Variable names can never, ever have spaces in them!
2. Variables: Strings
When you assign a string value to a variable (or create a variable and simultaneously assign the value), remember that strings go in quotes.
name = "Barney"
Note the spaces around the equal sign (which is actually the assignment operator). These are not absolutely required, but again, they’re dictated by Python’s stern style requirements. So use them. Always.
As for the quotation marks, you can use single quotes or double quotes; they both mean the same thing in Python.
You can print out the values of variables like this:
You can’t put variables inside quotes: they must always be in the clear.
print("name") # NO this is wrong! print(name) # YES do it this way
Online, go to http://introtopythonorg/hello_world.html. Run the simple examples.
Go to http://www.asmarterwaytolearn.com/python/2.html and review the exercises.
- Continue editing your script, examples.py.
- Create a new variable that contains “Author: “.
- Create a new variable, my_name, and populate it with your name (or any name).
- Be sure to handle it as a string.
- Add another print statement that outputs these variables on one line.
3. Variables: Numbers
Go to Chapter 3 of A Smarter Way.
When you’re assigning a value to a variable, and the value is a number, numbers never go in quotes.
number_of_cats = 2
You can print a numeric variable like this:
If a variable is a number, you can use the variable like a number in math:
number_of_cats = number_of_cats + 3
Go to http://www.asmarterwaytolearn.com/python/3.html and review the exercises.
- Continue editing your examples.py.
- Create a new variable, my_year, that contains the current year.
- Be sure to handle the variable as a number.
- Print “Copyright ” and the year.
By now your examples.py should be printing what looks like the beginning of a paper: a title, an author and a year.
4. Now go to Variables, Strings and Numbers online:
Particularly look at Changing case and Comments, for now. We’ll look at concatenating strings later.
my_name = "blarney" print(my_name) print(my_name.title()) print(my_name.upper())
# This is a comment print(my_name) # This is an inline comment """ This is a multi-line comment """
At the bottom of the page, note the section, Exploring the Python Community.¶
- Continue editing your examples.py file.
- Print the label “Author’s name: ” followed by my_name in lowercase, uppercase and title case. Use three lines to do this.
- Create a new variable, my_degree, that contains the value ” Ph.D.”.
- Concatenate my_name and my_degree so you can print them. Do you need another variable or can you concatenate inside the print statement?