Program To Add Two Numbers: File New Window CTRL+N
Program To Add Two Numbers: File New Window CTRL+N
")
2.
3. To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).
4. Write Python code (you can copy the code below for now) and save
(Shortcut: Ctrl+S) with .py file extension like: hello.py or your-first-
program.py
print("Hello, World!")
5. Go to Run > Run module (Shortcut: F5) and you can see the output.
Congratulations, you've successfully run your first Python program.
num1 = 3
num2 = 5
sum = num1+num2
print(sum)
Comments are used in programming to describe the purpose of the code. This helps
you as well as other programmers to understand the intent of the code. Comments
are completely ignored by compilers and interpreters.
Line 2: num1 = 3
Here, num1 is a variable. You can store a value in a variable. Here, 3 is stored in this
variable.
Line 3: num2 = 5
Line 5: print(sum)
The print() function prints the output to the screen. In our case, it prints 8 on the
screen
2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
The integer numbers (e.g. 2, 4, 20) have type int, the ones with a fractional part
(e.g. 5.0, 1.6) have type float. We will see more about numeric types later in the
tutorial.
Division (/) always returns a float. To do floor division and get an integer result
(discarding any fractional result) you can use the // operator; to calculate the
remainder you can use %:
>>>
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17
>>>
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
The equal sign (=) is used to assign a value to a variable. Afterwards, no result is
displayed before the next interactive prompt:
>>>
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>>
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
There is full support for floating point; operators with mixed type operands convert the
integer operand to floating point:
>>>
>>> 4 * 3.75 - 1
14.0
In interactive mode, the last printed expression is assigned to the variable _. This
means that when you are using Python as a desk calculator, it is somewhat easier to
continue calculations, for example:
>>>
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
This variable should be treated as read-only by the user. Don’t explicitly assign a value
to it — you would create an independent local variable with the same name masking the
built-in variable with its magic behavior.
Strings
Besides numbers, Python can also manipulate strings, which can be expressed in
several ways. They can be enclosed in single quotes ( '...') or double quotes ("...")
with the same result [2]. \ can be used to escape quotes:
>>>
In the interactive interpreter, the output string is enclosed in quotes and special
characters are escaped with backslashes. While this might sometimes look different
from the input (the enclosing quotes could change), the two strings are equivalent. The
string is enclosed in double quotes if the string contains a single quote and no double
quotes, otherwise it is enclosed in single quotes. The print() function produces a
more readable output, by omitting the enclosing quotes and by printing escaped and
special characters:
If you don’t want characters prefaced by \ to be interpreted as special characters, you
can use raw strings by adding an r before the first quote:
>>>
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>>
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
Two or more string literals (i.e. the ones enclosed between quotes) next to each other
are automatically concatenated.
>>>
>>> 'Py' 'thon'
'Python'
This feature is particularly useful when you want to break long strings:
>>>
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined
together.'
This only works with two literals though, not with variables or expressions:
>>>
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string
literal
...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
...
SyntaxError: invalid syntax
Strings can be indexed (subscripted), with the first character having index 0. There is no
separate character type; a character is simply a string of size one:
>>>
>>>
Note that since -0 is the same as 0, negative indices start from -1.
>>>
Note how the start is always included, and the end always excluded. This makes sure
that s[:i] + s[i:] is always equal to s:
>>>
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted
second index defaults to the size of the string being sliced.
>>>
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
The first row of numbers gives the position of the indices 0…6 in the string; the second
row gives the corresponding negative indices. The slice from ito j consists of all
characters between the edges labeled i and j, respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both are
within bounds. For example, the length of word[1:3] is 2.
>>>
However, out of range slice indexes are handled gracefully when used for slicing:
>>>
>>> word[4:42]
'on'
>>> word[42:]
''
Python strings cannot be changed — they are immutable. Therefore, assigning to an
indexed position in the string results in an error:
>>>
>>>
>>>
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
See also
Text Sequence Type — str
Strings are examples of sequence types, and support the common operations supported
by such types.
String Methods
Strings support a large number of methods for basic transformations and searching.
Formatted string literals
String literals that have embedded expressions.
Format String Syntax
Information about string formatting with str.format().
printf-style String Formatting
The old formatting operations invoked when strings are the left operand of the % operator
are described in more detail here.
3.1.3. Lists
Python knows a number of compound data types, used to group together other values.
The most versatile is the list, which can be written as a list of comma-separated values
(items) between square brackets. Lists might contain items of different types, but
usually the items all have the same type.
>>>
Like strings (and all other built-in sequence type), lists can be indexed and sliced:
>>>
All slice operations return a new list containing the requested elements. This means that
the following slice returns a new (shallow) copy of the list:
>>>
>>> squares[:]
[1, 4, 9, 16, 25]
>>>
>>>
You can also add new items at the end of the list, by using the append() method (we
will see more about methods later):
>>>
Assignment to slices is also possible, and this can even change the size of the list or
clear it entirely:
>>>
>>>
It is possible to nest lists (create lists containing other lists), for example:
>>>
>>>
The print() function writes the value of the argument(s) it is given. It differs from just
writing the expression you want to write (as we did earlier in the calculator examples) in
the way it handles multiple arguments, floating point quantities, and strings. Strings are
printed without quotes, and a space is inserted between items, so you can format things
nicely, like this:
>>>
>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536
The keyword argument end can be used to avoid the newline after the output, or end
the output with a different string:
>>>
>>> a, b = 0, 1
>>> while b < 1000:
... print(b, end=',')
... a, b = b, a+b
...
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987
,
Besides the while statement just introduced, Python knows the usual control flow
statements known from other languages, with some twists.
4.1. if Statements
Perhaps the most well-known statement type is the if statement. For example:
>>>
4.2. for Statements
The for statement in Python differs a bit from what you may be used to in C or Pascal.
Rather than always iterating over an arithmetic progression of numbers (like in Pascal),
or giving the user the ability to define both the iteration step and halting condition (as C),
Python’s for statement iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence. For example (no pun intended):
>>>
If you need to modify the sequence you are iterating over while inside the loop (for
example to duplicate selected items), it is recommended that you first make a copy.
Iterating over a sequence does not implicitly make a copy. The slice notation makes this
especially convenient:
>>>
>>>
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
>>>
>>>
>>> print(range(10))
range(0, 10)
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t.
It is an object which returns the successive items of the desired sequence when you
iterate over it, but it doesn’t really make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and
constructs that expect something from which they can obtain successive items until the
supply is exhausted. We have seen that the for statement is such an iterator. The
function list() is another; it creates lists from iterables:
>>>
>>> list(range(5))
[0, 1, 2, 3, 4]