Part 1 - Basic Concepts in Python. To help all learners of Python to understand concepts easily with suitable examples at each step.
Size: 751.77 KB
Language: en
Added: Aug 15, 2016
Slides: 15 pages
Slide Content
1
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
2
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
What is Python?
Welcome to Python!
Python is a high-level programming language, with applications in numerous
areas, including web programming, scripting, scientific computing, and artificial
intelligence.
It is very popular and used by organizations such as Google, NASA, the CIA and
Disney.
Python is processed at runtime by the interpreter. There is no need to compile
your program before executing it.
Interpreter: A program that runs scripts written in an interpreted language such as Python.
The three major version of Python are 1.x, 2.x and 3.x. These are subdivided
into minor versions, such as 2.7 and 3.3.
Backwards compatible changes are only made between major versions; code
written in Python 3.x is guaranteed to work in all future versions. Both Python
Versions 2.x and 3.x are used currently.
Python has several different implementations, written in various languages.
The version CPython is used further.
Python source files have an extension of .py
3
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
The Python Console
First Program:
On IDLE (Python GUI)
The Python Console
Python console is a program that allows you to enter one line of python code,
repeatedly executes that line, and displays the output. This is known as REPL –
a read-eval-print loop.
To close a console, type in “quit()” or “exit()”, and press enter.
Ctrl-Z : sends an exit signal to the console program.
Ctrl-C : stops a running program, and is useful if you’ve accidentally created a
program that loops forever.
>>> print("Hello Universe")
Hello Universe
>>> quit()
4
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
Simple Operations
1. Simple Operations can be done on console directly.
* : Multiplication / : Division
2. Use of parentheses for determining which operations are performed
first.
3. Minus indicates negative number
4. Dividing by zero in Python produces an error, as no answer can be
calculated.
In Python, the last line of an error message indicates the error’s type. In
further examples only last line of error is written.
>>> 2 + 2
4
>>> 5 + 4 – 3
6
>>> 2 * (3 + 4)
14
>>> (-7 + 2) * (-4)
20
>>> 11/0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
11/0
ZeroDivisionError: integer division or modulo by zero
5
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
Floats
Floats are used in Python to represent numbers that aren’t integers. Extra
zeros at the number’s end are ignored.
A float can be added to an integer, because Python silently converts the
integer to float. This conversion is the exception rather the rule in Python –
usually you have to convert values manually if you want to operate on them.
Other Numerical Operations
Exponentiation
The raising of one number to the power of another. This operation is
performed using two asterisks.
Quotient & Remainder
Floor division is done using two forward slashes. ( // )
The modulo operator is carried out with a percent symbol. ( % )
>>> 2**5
32
>>> 9** (1/2)
3.0
>>> 20 // 6
3
>>> 1.25 % 0.5
0.25
6
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
Strings
A String is created by entering text between two single or double quotation
marks.
Some characters can’t be included in string, they must be escaped by placing
backslash before them.
Manually writing “\n” can be avoided with writing the whole string between
three sets of quotes.
Simple Input & Output
In Python, we can use print function can be used to process output.
To get input from user, we can use input function. Which prompts user for i/p.
Returns what user enters as a string (with contents automatically escaped).
'System: Please Enter Input \nUser: Enters
Input\nSystem: Gives Output.'
7
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
String Operations
Strings in python can be added using Concatenation using “+” operator.
Strings also can be multiplied.
Strings can’t be multiplied by other strings.
Strings also can’t be multiplied by floats, even if the floats are whole numbers.
>>> “Hello ” + ‘Python’ (works with both types of
quotes)
Hello Python
>>> “2” + “2”
22
>>> "2" + 3
TypeError: cannot concatenate 'str' and 'int' objects
>>> "Sumit" * 3
'SumitSumitSumit'
>>> 4 * '2'
'2222'
>>> '27' * '54'
TypeError: can't multiply sequence by non -int of type 'str'
>>>"PythonIsFun" * 7.0
TypeError: can't multiply sequence by non -int of type 'float'
8
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
Type Conversion
You can’t add two strings containing numbers together to produce the integer
result. The solution is type conversion.
>>> int("2")+int("3")
5
>>> float(input("Enter a number:"))+float(
input("Enter Another Number:"))
Enter a number : 42
Enter Another Number : 55
97.0
9
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
Variables
A variable allows you to store a value by assigning it to a name, which can be
used to refer to the value later in the program.
To assign a variable, “=” is used.
Variables can be used to perform operations as we did with numbers and
strings as they store value throughout the program.
In Python, variables can be assigned multiple times with different data types as
per need.
For Variable names only characters that are allowed are letters, numbers and
underscores. Numbers are not allowed at the start. Spaces are not allowed in
variable name.
Invalid variable name generates error.
Python is case sensitive programming language. Thus, Number and number
are two different variable names in Python.
>>> x=9
>>> print(2*x)
18
Trying to reference a variable you haven’t assigned, causes error.
You can use the del statement to remove a variable, which means the
reference from the name to the value is deleted & trying to use the variable
causes an error.
Deleted variables can be reassigned to later as normal.
You can also take the value of the variable from user input.
>>> foo = 'string'
>>> foo
'string'
>>> bar
NameError: name 'bar' is not defined
>>> del foo
>>> foo
NameError: name 'foo' is not defined
>>> foo=input("Enter a number: ")
Enter a number: 24
>>> print foo
24
11
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
In-Place Operators
In-place operators allow you to write code like ’x = x + 3’ more concisely,
as ‘x +=3’. The same thing is possible with other operators such as - , * , / and
% as well.
These operators can be used on types other than number such as
strings.
Many languages have special operators such as ‘++’ as a shortcut for ‘x+=1’.
Python does not have these.
Dissecting Programs
Comments
Single Line Comments
Multi-line Comments
The print() Function
Displays the string value inside the parentheses written in the program on the
screen.
You can also use this function to put a blank line on the screen; just call
print() with nothing in between the parentheses.
The input() Function
Waits for the user to type some text on the keyboard and press ENTER.
This function call evaluates to a string equal to the user’s text, and the previous
line of code assigns the myName variable to this string value.
You can think of the input() function call as an expression that evaluates to
whatever string the user typed in.
#This Single Line Comment
print(‘Hello World!’)
'''
This is another type of comment
This is multi-line comment.
'''
myName = input()
13
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
The len() Function
You can pass the len() function a string value (or a variable containing a string),
and the function evaluates to the integer value of the number of characters in
that string.
Example:
The str(), int() and float() Functions
If you want to concatenate an integer such as 21 with a string to pass to
print(), you’ll need to get the value '21', which is the string form of 21. The str()
function can be passed an integer value and will evaluate to a string value
version of it, as follows:
The str(), int(), and float() functions will evaluate to the string, integer, and
floating-point forms of the value you pass, respectively.
>>> str(21)
'21'
>>> print('I am ' + str(21) + ' years old.')
I am 21 years old
>>> len('hello')
5
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'
14
BASIC CONCEPTS IN PYTHON SUMIT S. SATAM
TEXT AND NUMBER EQUIVALENCE
Although the string value of a number is considered a completely different
value from the integer or floating-point version, an integer can be equal to
a floating point .
>>> 42 == '42'
False
>>> 42 == 42.0
True
>>> 42.0 == 0042.000
True
Python makes this distinction because strings are text, while integers and
floats are both numbers .