7.9 KiB
Python programming basics¶
Here are some basic examples of concepts that we will learn in the class. We will also run these at http://pythontutor.com/visualize.html
Built-in names¶
Python has several words which are "built in" and do special things. When we start, we will use a lot of these. As we get further along, we will start using our own names and names we imported more and more.
print("hello world")
Variables¶
Another building block of programming are variables. These are names given to hold values. Each variable has a type, such as a string (like "hello" -- note the quotation marks) or integer (like 42).
x="hello world"
print(x)
print("x")
x
type(x)
x=42
print(x)
print(42)
x
type(x)
print(print)
print
type(print)
print(type)
type
type(type)
type(type(x))
Assignment¶
The process of setting a variable is called assignment. This is done with the equals (=
) symbol.
x = "my new string"
x
x = -1
x
x = x + 1
x
Let's look at these in the Python Tutor...
Functions¶
A building block of programming are functions. These are pieces of code that are called (also known as executed) with input and return output. They may also have side-effects.
Let's look at a function definition:
def my_function_name(argument1, argument2):
variable1 = argument1 + argument2
print("hello from my function") # this is a "side-effect"
return variable1
Above, we created a function named my_function_name
. This function takes two inputs (called arguments). There are several steps performed in the function. First, we add argument1
to argument2
and store the result in variable1
. Then we print something. Then we return variable1
as the output of our function.
The indentation (spaces) at the beginning of the lines in the function tell Python which lines of code are part of the function. Everything with the same level if indentation is a "block".
Above, we called the built in function print()
.
The print()
function takes any number of arguments as input, returns nothing, and as a side-effect prints the arguments to the screen.
Errors ("exceptions")¶
Python errors are called "exceptions". An important part of programming is figuring out why you got a particular error. Read the error message very carefully - it contains type of error, a description of the error, and a "traceback" that shows where the error came from.
1/0
x = variable_does_not_exist + 4
defx asdlkfj39:
adsk..{
Doing the assignments¶
We use automatic tests in this course. This way you can check most of your own work. Below is an example of how this works.
Example Problem¶
Assign a value of 2 to the variable named x
.
# Write your answer here
x = 2
assert x==2