A first program
Now that we are generally acquainted with spyder, let’s write our first program. Make sure you are working with the Spyder IDE. We will write our first program in the file that is provided upon start up (temp.py). To start, let’s just print a message. On the first line in the editor, type
[ ]:
print("Hello world!")
This one line makes use of python’s print command to send output from your program to the console. Press the green play button in the toolbar, or press the F5 key, and spyder will run your program. If all went well, you should see your message in the console. If you made a mistake, then python will try to tell you what you did wrong by passing an error message. There isn’t much to get wrong here, but if you did get an error message make sure you have opening and closing quotation marks as
well as opening and closing parenthesis. Also, make sure there is no white space in front of the print command itself.
Now is a good time to point out something obvious. When you write software, the computer is going to only do what you tell it. That means you have to be incredibly precise when writing code. Simple mistakes like forgetting a quotation mark, adding an extra blank space somewhere, or missing a close parenthesis or bracket will break your code.
Of course, we can do more than just print messages. We can also do math operations. Add the following lines to your program and execute the file again.
[ ]:
nSecondsInDay = 24 * 60 * 60
print(nSecondsInDay)
nSecondsInYear = nSecondsInDay * 365.25
print(nSecondsInYear)
Your program should now output your original message plus perform the above calculations and output the solutions.
Math operators
The math operators and usage are shown in the table below:
Operation |
Symbol |
Usage |
Result |
|---|---|---|---|
Addition |
|
|
|
Subtraction |
|
|
|
Multiplication |
|
|
|
Division |
|
|
|
Exponent |
|
|
|
Modulus |
|
|
|
Most of these are probably as expected, the exception being the exponent so make a note. If you are not familiar with the modulus operator, you can think of it as the remainder operator. m % n will return the remainder from the division of m by n.
This is a small subset of the mathematical operations that we might want to do. To do anything more advanced, we need to add additional functionality to our code- we need to load a module.
Math module
For math operations, we want to use the math module. So, at the top of your file, type the following: import math. This will give us access to many more mathematical operations. Once we import the module, in order to use it, we have to type the module name followed by a period followed by the name of the function that we want to use. In your code, try a few common operations such as:
[ ]:
print(math.sin(3))
print(math.cos(10))
print(math.sqrt(2))
There are many other functions built into the math module that we might want to use, but for now, know that this module gives you access to common trigonometric, power, logarithmic and special mathematical functions, number theory and rounding functions, and common constants.
There are many, many other modules available to us when we use python. We will meet a small handful through out this course. For now, lets summarize the basic concepts of a python module:
A module is a group of code items such as functions that are related to one another. Individual modules may be in a group called a library or a package.
Modules can be imported using
import. Functions that are part of the modulemodulenamecan be used with dot notation by typingmodulename.functionname. For example, we’ve used thesin()function which is part of themathmodule by typingmath.sin()with some number between the parenthesis.Modules may also contain constants such as
math.pi. Print this in your file and execute it to see the value of the constantmath.pi.
Try it yourself
You can combine functions! See if you can get your code to print the value of cos(pi/4). Make sure to use the pi constant defined in the math module.
Variables
We’ve already learned that we should use variables when programming and used them a bit. But, let’s talk about them in a little more detail. Variables can be used to store values calculated in expressions and used for other calculations. Assigning value to variables is straightforward. To assign a value, you simply type variable_name = value, where variable_name is the name of the variable you wish to define.
Modify your file and define a variable called temp_celsius, assign it a value of ‘10.0’, and then print that variable value using the print() function.
[ ]:
temp_celsius = 10.0
print(temp_celsius)
Note that we can combine output text with our variables:
[ ]:
print("Temp Fahrenheight: ",5/9 * (temp_celsius - 32))
Updating variables
Values stored in variables can also be updated. Let’s redefine the value of temp_celsius to be equal to 15.0 and print its value.
[ ]:
temp_celsius = 15.0
print("The temperature has changed to", temp_celsius,"deg C")
Warning
If you try to run some code that accesses a variable that has not yet been defined you will get a NameError message. Try printing out the value of the variable tempFahrenheit using the print() function.
[ ]:
print('Temperature in Celsius:', 5/9 * (tempFahrenheit - 32))
Note
You have to define a variable via assignment before you can use it (to do a calculation or in a function, etc.)!
Data types
So we know that we need to store data using variables. But, it should be expected that certain operations can only be performed on certain types of data. For example, in order to perform a mathematical operation such as multiplication or division, we should be working with numerical data. It wouldn’t necessarily make sense to perform these operations on some textual data.
For this reason, all programming languages have certain data types that belong to variables when we assign values to them. There are many different variable types in python. The four basic data types are shown in the table below.
Python name |
Data Type |
Example |
|---|---|---|
int |
Integer |
15 |
float |
Real number |
42.67 |
str |
Character string |
‘wolverine’ |
bool |
Boolean |
True or False |
Pay attention to the python name as those are the names that will be printed to the screen if you ask python what type of variable you are working with or if python throws an error because you are trying to do something with a variable that isn’t allowed for that variable’s data type. We will meet other data types as the need arises.
Try it yourself
You can determine the data type of a variable using python’s type() function. In the file that you are working with or in the console, have python determine the type of several different variables that you create by typing print(type(variablename)) where variablename is the name of your variable.
Input
One of the most common things that we do when working with software is take input from the user when a program is running. Python makes this task pretty easy with the input() function. Try the following in your temp file:
[ ]:
username = input('Please enter your name: ')
Then run your program again. You should be prompted to enter some text in the console.
Your program is still running, but it is waiting for you to use the keyboard to enter something. So, you can type your name in the console and hit enter. The result of this is your name will be stored in the variable username. And now you can use that variable as you would any other variable in python. For example, we could print it the username:
[ ]:
print(username)
or work with it in other ways:
[ ]:
print(username.upper())
print(username.lower())
print(len(username))
Note The input() function takes at least 1 argument (an argument is the thing that goes between the parenthesis) and then stores the text that you enter as a str. It doesn’t matter what you enter in the prompt: letters, numbers, etc. the resulting data type will always be a character string.
