PYTHON TUTORIAL #3 : GETTING STARTED
You read about the introduction of python and Installation of python. Now it's time to get started with the actual stuff. In today's post, I am going to write about some of the basic stuffs of programming.
Using A Source File
Now let's get back to programming. There is a tradition that whenever you learn a new programming language, the first program
that you write and run is the 'Hello World' program - all it does is just say 'Hello World' when you run it. As Simon Cozens says,
it is the "traditional incantation to the programming gods to help you learn the language better."
Start your choice of editor, enter the following program and save it as hello.py .
If you are using PyCharm, we have already discussed how to run from a source file in my previous post
For other editors, open a new file hello.py and type this:
print("hello world")
Where should you save the file? To any folder for which you know the location of the folder. If you don't understand what that
means, create a new folder and use that location to save and run all your Python programs:
- /tmp/py on Mac OS X
- /tmp/py on GNU/Linux
- C:\py on Windows
To create the above folder (for the operating system you are using), use the mkdir command in the terminal, for example, mkdir
/tmp/py .
IMPORTANT: Always ensure that you give it the file extension of .py , for example, foo.py .
RUNNING THE PROGRAM
In Pycharm you can click on Run after typing "print("hello world")"as shown in the picture:
Or if you are using Python IDE you can simply type above code and click enter as shown in figure.
If you got the output as " Hello world" congratulations! - you have successfully run your first Python program. You have
successfully crossed the hardest part of learning programming, which is, getting started with your first program!
In case you got an error, please type the above program exactly as shown above and run the program again. Note that Python is
case-sensitive i.e. print is not the same as Print - note the lowercase p in the former and the uppercase P in the latter.
Also, ensure there are no spaces or tabs before the first character in each line - we will see why this is important later.
How It Works
A Python program is composed of statements. In our first program, we have only one statement. In this statement, we call the print statement to which we supply the text "hello world".
Getting Help
If you need quick information about any function or statement in Python, then you can use the built-in help functionality. This
is very useful especially when using the interpreter prompt. For example, run help('len') - this displays the help for the len
function which is used to count number of items.
TIP: Press q to exit the help.
Similarly, you can obtain information about almost anything in Python. Use help() to learn more about using help itself!
In case you need to get help for operators like return , then you need to put those inside quotes such as help('return') so that
Python doesn't get confused on what we're trying to do.
Summary
You should now be able to write, save and run Python programs at ease.
Now that you are a Python user, let's learn some more Python concepts.
Basics
Just printing hello world is not enough, is it? You want to do more than that - you want to take some input, manipulate it and
get something out of it. We can achieve this in Python using constants and variables, and we'll learn some other concepts as well
in this chapter
COMMENTS
Comments are any text to the right of the # symbol and is mainly useful as notes for the reader of the program
For example:
print('hello world') # Note that print is a function
Or:
# Note that print is a function
print('hello world')
Use as many useful comments as you can in your program to:
- explain assumptions
- explain important decisions
- explain important details
- explain problems you're trying to solve
- explain problems you're trying to overcome in your program, etc.
Code tells you how, comments should tell you why.
This is useful for readers of your program so that they can easily understand what the program is doing. Remember, that person
can be yourself after six months!
Literal Constants
An example of a literal constant is a number like 5 , 1.23 , or a string like 'This is a string' or "It's a string!" .
It is called a literal because it is literal - you use its value literally. The number 2 always represents itself and nothing else - it is
a constant because its value cannot be changed. Hence, all these are referred to as literal constants.
Numbers
Numbers are mainly of two types - integers and floats.
An example of an integer is 2 which is just a whole number.
Examples of floating point numbers (or floats for short) are 3.23 and 52.3E-4 . The E notation indicates powers of 10. In this
case, 52.3E-4 means 52.3 * 10^-4^ .
Strings
A string is a sequence of characters. Strings are basically just a bunch of words.
You will be using strings in almost every Python program that you write, so pay attention to the following part.
Single Quote
You can specify strings using single quotes such as 'Quote me on this' .
All white space i.e. spaces and tabs, within the quotes, are preserved as-is.
Double Quotes
Strings in double quotes work exactly the same way as strings in single quotes. An example is "What's your name?" .
Triple Quotes
You can specify multi-line strings using triple quotes - ( """ or ''' ). You can use single quotes and double quotes freely
within the triple quotes. An example is:
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
Strings Are Immutable
This means that once you have created a string, you cannot change it. Although this might seem like a bad thing, it really isn't.
We will see why this is not a limitation in the various programs that we see later on.
- Note for C/C++ Programmers
- Note for Perl/PHP Programmers
The format method
Sometimes we may want to construct strings from other information. This is where the format() method is useful.
Save the following lines as a file str_format.py :
age = 20
name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age))
print('Why is {0} playing with that python?'.format(name))
Output:
$ python str_format.py
Swaroop was 20 years old when he wrote this book
Why is Swaroop playing with that python?
How It Works
A string can use certain specifications and subsequently, the format method can be called to substitute those specifications with
corresponding arguments to the format method.
Observe the first usage where we use {0} and this corresponds to the variable name which is the first argument to the format
method. Similarly, the second specification is {1} corresponding to age which is the second argument to the format method.
Note that Python starts counting from 0 which means that first position is at index 0, second position is at index 1, and so on.
Notice that we could have achieved the same using string concatenation:
name + ' is ' + str(age) + ' years old'
but that is much uglier and error-prone. Second, the conversion to string would be done automatically by the format method
instead of the explicit conversion to strings needed in this case. Third, when using the format method, we can change the
message without having to deal with the variables used and vice-versa.
Also note that the numbers are optional, so you could have also written as:
age = 20
name = 'Swaroop'
print('{} was {} years old when he wrote this book'.format(name, age))
print('Why is {} playing with that python?'.format(name))
which will give the same exact output as the previous program.
We can also name the parameters:
age = 20
name = 'Swaroop'
print('{name} was {age} years old when he wrote this book'.format(name=name, age=age))
print('Why is {name} playing with that python?'.format(name=name))
which will give the same exact output as the previous program.
Python 3.6 introduced a shorter way to do named parameters, called "f-strings":
age = 20
name = 'Swaroop'
print(f'{name} was {age} years old when he wrote this book') # notice the 'f' before the string
print(f'Why is {name} playing with that python?') # notice the 'f' before the string
which will give the same exact output as the previous program.
What Python does in the format method is that it substitutes each argument value into the place of the specification. There can
be more detailed specifications such as:
# decimal (.) precision of 3 for float '0.333'
print('{0:.3f}'.format(1.0/3))
# fill with underscores (_) with the text centered
# (^) to 11 width '___hello___'
print('{0:_^11}'.format('hello'))
# keyword-based 'Swaroop wrote A Book'
print('{name} wrote {book}'.format(name='Swaroop', book='Learn Python'))
Output:
0.333
___hello___
Swaroop wrote A Book
Since we are discussing formatting, note that print always ends with an invisible "new line" character
( \n ) so that repeated calls to print will all print on a separate line each. To prevent this newline character from being printed, you can specify that it
should end with a blank:
print('a', end='')
print('b', end='')
Output is:
ab
Or you can end with a space:
print('a', end=' ')
print('b', end=' ')
print('c')
Output is:
a b c
Escape Sequences
Suppose, you want to have a string which contains a single quote ( ' ), how will you specify this string? For example, the string is "What's your name?". You cannot specify 'What's your name?' because Python will be confused as to where the string starts and ends. So, you will have to specify that this single quote does not indicate the end of the string. This can be done with the help of what is called an escape sequence.
You specify the single quote as \' : notice the backslash. Now, you can specify the string as 'What\'s your name?'.
Another way of specifying this specific string would be "What's your name?" i.e. using double quotes. Similarly, you have to use an escape sequence for using a double quote itself in a double quoted string. Also, you have to indicate the backslash itself using the escape sequence \\ .
What if you wanted to specify a two-line string? One way is to use a triple-quoted string as shown previously or you can use an escape sequence for the newline character - \n to indicate the start of a new line. An example is:
'This is the first line\nThis is the second line'
Another useful escape sequence to know is the tab: \t . There are many more escape sequences but I have mentioned only the most useful ones here.
One thing to note is that in a string, a single backslash at the end of the line indicates that the string is continued in the next line, but no newline is added. For example:
"This is the first sentence. \
This is the second sentence."
is equivalent to
"This is the first sentence. This is the second sentence."
Raw String
If you need to specify some strings where no special processing such as escape sequences are handled, then what you need is to specify a raw string by prefixing r or R to the string. An example is:
r"Newlines are indicated by \n"
Note for Regular Expression Users
Always use raw strings when dealing with regular expressions. Otherwise, a lot of backwhacking may be required. For example, backreferences can be referred to as '\\1' or r'\1'
That's all for today
In this post i have written some basic stuffs such as playing with print and introduced strings. I hope you found this useful.
In next post i will wriye about variables.
I hope you are excited for the further posts, Let me know in the comment section. Also comment if you have any doubt.
SUGGESTIONS AND EDITS ARE WELCOMED. PLEASE DO SUBSCRIBE AND SHARE WITH OTHER PEOPLE.
To see other posts of this python tutorial series, please Click here
No comments:
Post a Comment