Let's write some code!
Below is your first Python program. If you run the program (click Try It Now! and then Run), you'll see that it simply produces the output Hello, Commonlounge!.
When you say print('Something'), Python will "print" the contents you give it to the output (without the quotes).
In the above program, 'Hello, Commonlounge!' is a string. A string is a sequence of characters that can be processed by a computer. The string must always begin and end with the same character. This may be single (') or double (") quotes (there is no difference!) The quotes tell Python that what's inside of them is a string.
Note: This course is structured so that you can learn quite a bit of Python before having to install things on your computer. However, if you prefer to run the Python programs on your computer, it shouldn't take more than 5 minutes to set things up. See Set-up and installation instructions for Python.
How about some numbers? Let's see what Python can do.
type=codeblock|id=py3_add|autocreate=python3print(2 + 3)
Again, click Try It Now! and then Run on the code above to actually run it. You can also play around. Try changing the numbers and make sure you're getting the correct answers.
Nice! See how the answer popped out? Python knows math! You could try other commands like:
type=codeblock|id=py3_simple_math|autocreate=python3print(4 * 5)print(5 - 1)print(40 / 2)
Along the course, we recommend you to run all the programs, and also try changing things to see what happens. Programming is best learnt by doing.
To perform exponential calculation, say 2 to the power 3, we type:
type=codeblock|id=py3_exponentiation|autocreate=python3print(2 ** 3)
Have fun with this for a little while and then get back here. :)
There are some more operators in Python, but we won't go over them right now. At the end of the article, there is a table with a list of all arithmetic operators in Python.
Each of the lines that you typed above (inside print()) is called an expression. Expressions can be much longer too. For example, try this:
type=codeblock|id=py3_expressions|autocreate=python3print((5 + 2) * (7 - 1) / 3)
In Python (and other programming languages as well), all expressions evaluate to a single value. You saw this above for some simple expressions such as 2 + 3 which evaluates to 5.
Here's a step-by-step breakdown of how the above expression is evaluated in Python.
(5 + 2) * (7 - 1) / 3=> (7) * (7 - 1) / 3=> 7 * (7 - 1) / 3=> 7 * (6) / 3=> 7 * 6 / 3=> 42 / 3=> 14.0
Python does the above behind the scenes, and tells us what the final result of evaluating the expression is.
As you can see, Python is a great calculator. If you're wondering what else you can do…
Let's come back to strings. You already saw one in the beginning of this tutorial.
How about your name? Type your first name in quotes like this:
As we said before, a string is a sequence of characters that can be processed by a computer. The string must always begin and end with the same character. This may be single (') or double (") quotes (there is no difference!) The quotes tell Python that what's inside of them is a string.
Strings can be strung together. Try this:
type=codeblock|id=py3_string_concat|autocreate=python3print("Hi there " + "Commonlounge")
Hi there Commonlounge
Notice how we had to end the first string ("Hi there ") with a space (" "). If we did not, then our result would be 'Hi thereCommonlounge', which isn't what we want.
You can also multiply strings with a number:
type=codeblock|id=py3_string_repeat|autocreate=python3print("Commonlounge" * 3)
And you can combine these things into a more complicated expression as well:
type=codeblock|id=py3_string_expressions|autocreate=python3print("Hi there " + ("Commonlounge" * 3) + "!")# Output: Hi there CommonloungeCommonloungeCommonlounge!print("Hi there Commonlounge" + "!" * 10)# Output: Hi there Commonlounge!!!!!!!!!!
Note: # denotes a comment in Python. You can write whatever you want after the # and Python will ignore it. Comments can make your code easier for other people to understand.
If you need to put an apostrophe inside your string, you have two ways to do it.
Using double quotes:
type=codeblock|id=py3_string_with_quotes|autocreate=python3print("Runnin' down the hill")# Output: Runnin' down the hill
or escaping the apostrophe with a backslash (\):
type=codeblock|id=py3_string_with_escapes|autocreate=python3print('Runnin\' down the hill')# Output: Runnin' down the hill
Nice, huh? To see your name in uppercase letters, simply type:
type=codeblock|id=py3_string_upper|autocreate=python3print("Commonlounge".upper())# Output: COMMONLOUNGE
You just used the upper method on your string! A method (like upper()) is a sequence of instructions that Python has to perform on a given object ("Commonlounge") once you call it.
If you want to know the number of letters contained in your name, there is a function for that too!
type=codeblock|id=py3_string_len|autocreate=python3print(len("Commonlounge"))# Output: 12
Wonder why sometimes you call functions with a . at the end of a string (like "Commonlounge".upper()) and sometimes you first call a function and place the string in parentheses? Well, in some cases, functions belong to objects, like upper(), which can only be performed on strings. In this case, we call the function a method. Other times, functions don't belong to anything specific and can be used on different types of objects, just like len(). That's why we're giving "Commonlounge" as a parameter to the len function.
There's more to strings and functions in Python, and we'll be learning about it later in the course in the following tutorials - Python3 Strings and Python3 Functions.
In fact, just like len(), print() is also a function! Note that expressions are evaluated from the inside out. That is, Python first calculates len("Commonlounge"), which is 12, and then executes the print() function with that value.
Let's try something new. Can we get the length of a number the same way we could find out the length of our name? Type in len(304023):
Traceback (most recent call last):File "", line 1, inTypeError: object of type 'int' has no len()
We got our first error! Making mistakes (even intentional ones) are an important part of learning! In particular, an error doesn't mean something bad is going to happen with the computer. It's just Python's way of saying, “Something's wrong.” or “I don't understand.”
It says that objects of type "int" (integers, whole numbers) have no length. So what can we do now? Maybe we can write our number as a string? Strings have a length, right?
type=codeblock|id=py3_int_to_str|autocreate=python3print(len(str(304023)))# Output: 6
It worked! We used the str function inside of the len function. In particular, the step-by-step evaluation of the above is:
len(str(304023))=> len("304023")=> 6
You can use the str() function to convert anything to a string.
- The str function converts things into strings
- The int function converts things into integers
Important: we can convert numbers into text, but we can't necessarily convert text into numbers – what would int('hello') be anyway?
OK, enough of strings. So far you've learned about:
- print – used to make Python "print" the contents you give it
- numbers and strings – numbers are used for math and strings for text objects
- operators – like + and *, combine values to produce a new one
- functions – like upper() and len(), perform actions on objects.
- errors – you now know how to read and understand errors that show up if Python doesn't understand a command you've given it
These are the basics of every programming language you learn. Ready for something harder? We bet you are!
The following is a list of all arithmetic operations supported by Python.
Operator | Example | Result | Description---------|---------|--------|------------------------------------------------+ | 4 + 5 | 9 | addition- | 4 - 5 | -1 | subtraction* | 4 * 5 | 20 | multiplication/ | 8 / 3 | 2.666 | division// | 14 // 3 | 4 | integer division (fractional part is ignored)% | 14 % 3 | 2 | modulo (remainder left after division)** | 5 ** 2 | 25 | exponent
Based on content from https://tutorial.djangogirls.org/en/python_introduction/