Variables
Every programming language has variables, and so does python.
Think of variables as containers that can hold value, each container has a name, and contains a value.
Assigning a value to a new variable, or changing a value of an existing one, is done with “=”.
my_first_variable = 2 another_variable = 0 a = 5 a = 3 x = 7
For now all the values are basic numbers, but they can contain a lot of different types, we’ll get to that.
First some explanation about what is a legal variable name and what is not, here are the rules for defining a variable name:
- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (age, Age and AGE are three different variables)
Basic Value Types
Regular numbers without a decimal point are called integers, and they can be positive and negative and 0. To use an integer you just write the number where you need it, like in the example above where we assigned some integer values to variables.
Numbers that have a decimal point are usually Floating Point numbers, or floats.
Example below assigns some floats to variables.
Note that in this example we freely assign different types to the same variable name, and that changes that variable’s value and type.
v = 5 v = 1.12 v = 0.4 x = -25.7
Strings are a collection of letters, they allow saving messages and information in whatever format you want.
x = "Hello World" y = 5 y = "Hey look i got 7 bananas, and 15.5 dollars"
There are more complex built-in types in python and they will be explained in later chapters.
Using Variables and Output
Variables can also be used and they provide the value they contain.
First let’s see a basic example of how to output something to the screen, we’ll need this to better understand variable use, and in our programs in general.
myvar = 5 print(myvar) myvar = -12.7 print(myvar) myvar = "Hey how are you?" print(myvar)
Running above example should output:
5 -12.7 Hey how are you?
Code Comments
Programming is a complex task, and in large programs will result in a lot of code that is not always easy to understand.
Python, and any programming language for that matter, allows writing comments together with the code.
The comments help explain things.
A comment starts with “#” and anything beyond that is free text that Python ignores.
# this comment starts from the very beginning of the line a = 5 # this one starts at the end of a code line print(a) # this line prints the value inside a, which is 5 x = 1 # such comment is called inline-comment # style guide for inline comments asks for 2 spaces at least before the start of an inline comment y = 1 # this is bad y = 2 # this is good
Code examples from this point onward will include comments that give more relevant explanations.
Basic Operations
Basic operations can be performed with values and variables, operation results can be different depending on value types, look at below examples.
s = 1 + 3 # this will save 4 into s variable (result of 1 + 3) print(s) # this will print 4 w = s + 7.5 # this will 11.5 save in w (the result of 4 + 7.5) print(w) # this will print 11.5 z = "Hello" # this will save "Hello" in z print(z + " World") # this will print "Hello World", note + in this case adds the two strings together. print(11 + 2) # this will print 13 print("11" + "2") # this will print 112
Note the difference between line 7 and 8.
Even though both look like we are adding 11 and 2, on line 8 we are actually working with strings, not numbers.
So the operation “+” on strings chains the two strings together. (concatenates)
Basic supported operations on numbers
- “+” Addition, “–” Subtraction, “*” Multiplication, “/” Division
- “%” Modulo (Returns the left over after a division operation)
- “**” Power (2 ** 3 results in 8)
Basic supported operations on strings
- “+” Concatenation
- “*” Used with a number, allows string replication
- “%” Modulo for strings is used for formatting, further explained at the end of this chapter.
print("Hello" * 10)
HelloHelloHelloHelloHelloHelloHelloHelloHelloHello
Understanding Errors
This chapter is very important, don’t skip this, errors will happen, and it is vital to learn how to understand them and solve them.
Run the following code (Remember to run with Ctrl+F5):
a = 5 b = "7" print(a + b)
You should get an error message that looks like this:
Traceback (most recent call last): File "/home/shiftybyte/projects/helloworld/hello.py", line 3, in <module> print(a + b) TypeError: unsupported operand type(s) for +: 'int' and 'str'
Let’s break it down:
- most recent call last – this is always there, and its a reminder that you should usually look at the last line for the error, in this case we only have one call in the traceback, but more complex code can have multiple calls, and the last one is the most recent, and it’s probably the one we are interested in.
- File “/home/shiftybyte/projects/helloworld/hello.py”, line 3, in <module> – this tells you where the error occured, it contains the file name, the line number, and a module name. Modules will be explained in later chapters.
- print(a + b) – this shows the actual line of code that caused the error.
- TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
- TypeError – this is the error category, TypeError usually happens when we have a problem with value types.
- unsupported operand type(s) for +: ‘int’ and ‘str’ – This is the explanation of the error, python tells us that it does not support the operand “+” between the types ‘int’ and ‘str’.
This makes sense as we tried to add a string and a number. 5 + “7” which is not the same as 5 + 7.
Correcting the above error we should either change a to be “5” if want the result to be “57”, or change b to be 7 if we want the result to be 12.
a = 5 b = 7 print(a + b)
User Input
No we finally arrive at asking the user of your program for input, now the programs can start being useful.
To ask for input we call a function (later about functions in general) that’s called “input”.
user_name = input("Enter your name: ") print("Hello, " + user_name + "!") print("Welcome to my program!")
Running above code should ask you to enter a name, and when you enter it, that name will be saved as a string in user_name, and later on added to another string and printed.
Enter your name: shiftybyte Hello, shiftybyte! Welcome to my program!
Type Conversion
Now you may have noticed that the input() function that is used to get information from the user always returns a string.
What if we want to ask for a number? And then use it for mathematical operations?
For this we can use functions that convert one type to another.
- int() – converts a string/float to an integer number.
- float() – converts a string/integer to a floating point number.
- str() – “converts” anything to a string.
str() works a bit differently than the others, this will be explained in later chapters.
Below example shows a simple program that uses conversion, and explains why along the way:
print("Welcome!") age_str = input("Please enter you age:") age_num = int(age_str) # this line converts the string number to an integer number next_year = age_num + 1 print("Wow, next year you are going to be " + str(next_year)) # above line calls str() because without it we can't use "+" on a string and an integer. # so it converts next_year to a string, and then we can use "+" to concatenate it.
Welcome! Please enter you age:25 Wow, next year you are going to be 26
Above program can be written in a shorter way, by nesting function calls.
When a function completes, it returns the result to whoever is waiting for it’s value.
If the value is needed for another function call, it can go directly there.
Below example does exactly the same:
print("Welcome!") age = int(input("Please enter you age:")) print("Wow, next year you are going to be " + str(age + 1))
Output Formatting
To get better control over how things look when they are printed to the screen, there are several methods that help format a string.
The different methods below do this by placing different parts with possibly different types into it.
Modulo
name = "Dude" age = 21 money = 112.7 print("Wow %s, you are only %d and you already have %f dollars!" % (name, age, money))
Wow Dude, you are only 21 and you already have 112.700000 dollars!
Let’s explain how this works, “%” (Modulo) operator can be used directly after a string, to provide information that will be inserted into the string based on the expected type and format and the order that special “%?” marks appear.
- %s – means python should expect a string, and since it’s the first %? encountered, it expects it to be in the first location after the Modulo; The first location contains name variable.
- %d – means python expects an integer number, and it should be in the second position after the Modulo; In this case its age.
- %f – means python expects a floating point number in the third location; In this case its money.
Looks like the money was printed in a weird way, we can fix that with more details that control how a value is displayed.
Look at the code and explanation below:
name = "Dude" age = 21 money = 112.7 print("Wow %s, you are only %d and you already have %.1f dollars!" % (name, age, money))
Wow Dude, you are only 21 and you already have 112.7 dollars!
Note the “%f” was changed to “%.1f“, this change tells python to only print 1 digit after the decimal point.
This covers a small part of the options, for more options and information look for the official python documentation: https://docs.python.org/2/library/stdtypes.html#string-formatting
.format()
name = "Dude" age = 21 money = 112.7 print("Wow {}, you are only {} and you already have {} dollars!".format(name, age, money))
Wow Dude, you are only 21 and you already have 112.7 dollars!
This method uses .format() function that is added at the string’s end. (More on what it means in the classes chapter)
And every {} is replaced with whatever value is inside the format function’s parameters.
This formatting allows advanced options like referencing specific arguments, and using an argument more than once.
age = 21 money = 112.7 print("{0}?? really? only {0} and you already have {1} dollars?! wish i was {0}...".format(age, money))
21?? really? only 21 and you already have 112.7 dollars?! wish i was 21...
Note how the {} now has a number in them referencing a specific argument inside format() function.
Now an argument can be used out of order and more than once, and even not at all.
(The number is starting the count from 0)
For full description of all possible options head to python’s documentation at: https://docs.python.org/3/library/string.html
f-strings
Since Python version 3.6 there is a new way to format a string.
age = 21 money = 112.7 print(f"You are {age}?? and you already have {money} dollars?! I'm only {age - 1}.") print(f"But when i'll be {age + 1} i'll have {money * 3} dollars!")
You are 21?? and you already have 112.7 dollars?! I'm only 20. But when i'll be 22 i'll have 338.1 dollars!
This format requires a string to be marked as a format string with an “f” before it.
This “f” tells python to treat whatever is inside {} as python code and insert it’s output into the string.
This allows “advanced” uses like below code to be acceptable by Python.
print(f"Hello {input('Enter your name: ')}! how is life?")
Enter your name: shiftybyte Hello shiftybyte! how is life?
Note how the “Enter you name: ” appeared first, even though it’s written after “print” function.
This happens because python first “calculates” the value of all the arguments of print, and only then sends the values to the function.
So it constructs the format string before calling print, and this requires calling input().
(Please don’t write code like this.)
More information about f-strings can be found in: https://www.python.org/dev/peps/pep-0498/
Exercise
Write a program what asks for the names of two persons, and the money each one has.
Then the program prints a greeting for each, tell him how much money he has.
The program also prints a line telling the two persons how much money they have together.
Expected output should be similar to this:
Enter first name: shifty Enter shifty's money: 3671.1 Enter second name: byte Enter byte's money: 671.98 shifty has 3671.1 dollars! byte has 671.98 dollars! Together you have 4343.08 dollars!