Python Intro
Python Intro
All types of computers follow the same basic logical structure and perform the
following five basic operations for converting raw input data into information
useful to their users.
Example: C, C++, C#, Basic, Fortran, Java, Jscript, PHP, Python, Perl etc..
System Programming
Graphical User Interface Programming
Database Programming
Game development
Why do people use Python….. ?
The following primary factors cited by Python users seem
to be these:
Python is object-oriented with very simple
syntax rules.
It’s free (open source)
It’s powerful
It’s portable(works on variety of platforms –
Windows,linux,Mac).
Its completeness(need not to install additional
libraries).
Installing Python
https://www.python.org/downloads/
- Download the latest version of python IDLE and install,
recent version is 3.8.1 , 3.7.1
Running Python
>>> print 3 * 12 36
>>> print 12 / 3 4
>>> print 12.0 / 3.0 4.0
>>> print 11.0 / 3.0 3.66
Relational operators:
>>> print 2 < 3 True
>>> print 2 != 3 True
>>> print False < True True
>>> print ‘Apple’==‘Apple’ True
Unary operators
The operators that act on one operand are referred to as Unary operators.
Example: +,-.
If a = 5 then +a means 5, -a means -5
If a = 0 then +a means 0, -a means 0
If a = -4 then +a means -4, -a means 4
Binary operators
The operators that act upon two operands are referred to as Binary operators.
Example: +,-,*,/,//, %(modulus), **(Exponentiation)
4+20 results in 24
a+5(where a=2) results in 7
19 % 6 results in 1
4**3 results in 64
5*6 results in 30
a=15.9, b=3, a/b = 5.3
Augmented Assignment operators
Example1: if you want to add value of b to value of a and assign the result to a,
then instead of writing
a=0, b=5 a = a + b = 0+5 =5
you may write
a+=b
Example2: to add value of a to value of b and assign the result to b, you may write
b+=a # instead of b= b + a
x+=y x= x+y
x - =y x=x-y
x *=y x=x*y
x/=y x=x/y
x//=y x=x//y
x**=y x=x**y
Operator Precedence
Order of execution through Operator Precedence.
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR
Examples:
f=‘god’, g=‘God’,h=‘god’,j=‘God’, k=“Godhouse”
f==h will return True
“God”==“Godhouse” will return True
g== j will return True
“god” < “Godhouse” will return False
• Numbers can be integers (1 and 2), floats (1.1 and 1.2), fractions,
or even complex numbers.
Examples:
Try typing without quotes: >>>”It’s a beautiful day !”
What’s the result ? >>> a= “Good Morning”
>>> a
‘Good Morning’
>>> a= ‘Good Morning’
>>>a
‘Good Morning’
Strings Operations:
Concatenation , Replication :
Strings Operations:
Slicing : refers to a part of the string.
Specify the start index and the end index, separated by a colon.
Syntax: string[start:end:step]
Example:
Membership operators
‘in’ and ‘not in’ are membership operators.
‘in’ – returns true if a character/substring exists in a given string.
‘not in’ – returns true if a character/substring does not exist in the
given string.
Syntax: <substring> in <string>
<substring> not in <string>
Built in String Methods:
Len() – returns the length of the string.
Syntax: Len(str)
Capitalize() – first letter is in uppercase
Syntax: str.capitalize()
Split() – breaks up a string at the specified separator and returns a list of
substrings.
Syntax : str.split( [ separator [, maxsplit ] ] )
** Note : a) If separator is not specified, any white space string is a separator.
b) Default value of maxsplit is 0.
Lower() – converts all the uppercase letters into lowercase
Syntax: str.lower()
Upper() - converts all the lowercase letters into uppercase
Syntax: str.upper()
Replace() – replaces all the occurrences of the old string with the new
string.
Syntax : str.replace(old,new)
Empty String
** if we wish to display the output on the next line, then the use of escape
sequence ‘\n’ becomes mandatory.
We can also use escape sequence (\t) to tabulate the output.
Multiline Strings
Traversing a String
Means accessing all the elements of the string one after the other by
using the subscript or index value.
List: Data Type
Lists:
Example:
List1= [‘physics’,’chemistry’,1997,2000]
List2= [1,2,3,4,5]
Creating lists
A)
Concatenation , Replication :
List Operations:
Slicing :
Can we have 2 lists working
together ????
List In-Built Functions:
append() – append a value at the end.
clear() – clear entire list.
insert(index value, value) - insert the value at the mentioned index value.
remove(value) – remove the particular value.
pop(index no.) – remove the value which is at the mentioned index
number. Without any index value , pop() will remove the last element
which is added.
del list_name[start: end]
extend() – add multiple values.
min(list) – finds minimum value
max(list) – finds maximum value
sum(list) – sum of all the numbers of the list.
sort() – sorts the list ascending by default.
** list.sort(reverse=True|False), reverse=True will sort the
list descending. Default is reverse=False
Tuples: Data Type
Tuples:
Example:
Fruits=(‘Mango’, ’apple’, ’Grapes’)
Tuple named ‘Fruits’ with three elements.
Main difference between lists and tuples are: Lists are enclosed within
brackets [ ] and their elements and size can be changed, while tuples are
enclosed within parenthesis ( ) and cannot be updated. Tuples can be thought
of as read-only lists.
When we should be using Tuples ?
When you know that you have a list and you don’t want to change the values
of it and yes, in certain projects we have this requirement. Since, we don’t change
values in a tuple, so, iteration in tuples is faster than a list. So, it enhances the
speed of execution.
Tuple Operations:
Concatenation , Replication :
Tuple Operations:
Slicing :
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
But ,you can convert the tuple into a list, change the list, and convert the
list back into a tuple.
Example:
Tuple In-Built Functions:
len() – how many items a tuple has.
del keyword can delete the tuple completely.
Syntax : del tup
index() - Search for the first occurrence of the value 8, and
return its position
count() - Returns the number of times a specified value occurs
in a tuple
Dictionary: Data Type
Dictionary:
Example:
>>> data = {1:’Navin’,2:’kiran’,4:’Harsh’}
1) Dictionaries have a “Key” and a “value of that key”.
2) Dictionaries store huge amount of data.
3) Fetch value in an efficient way.
4) Every value is assigned with a key.
5) Key should be immutable & unique.( can be string or numbers)
Note: Internally, dictionaries are arranged on the basis of keys.
Traversing a Dictionary:
Change Values
You can change the value of a specific item by referring to
its key name:
Ways of creating Dictionaries
To create an empty dictionary, there are two ways:
i) employee = { }
ii) employee = dict{ }
Specify Key:Value pairs as keyword arguments to dict() function.
employee = dict(name=‘John’, salary = 10000,age=24)
>>>employee
{‘salary’:10000,’age’:24,’name’: ‘John’}
** Python automatically converted argument names to string type
keys.
Specify comma-separated key:value pairs.
employee = dict({‘name’:‘John’, ‘salary’ : 10000,’age’:24})
>>>employee
{‘salary’:10000,’age’:24,’name’: ‘John’}
• Clear () – empties the dictionary
thisdict.clear()
print(x)
if x== "banana":
continue
Break statement
We can stop the loop before it has looped through all the items.
fruits = ["apple","banana","cherry"]
for x in fruits:
if x== "banana":
break
** you can write print(x) before break also.
Range() function
To loop through a set of code a specified number of times we can use the range()
function.
Range() function a sequence of numbers, starting from 0 by default and increments
by 1, and ends at a specified number.
for x in range(6):
print(x)
However, it is possible to specify the starting value by adding a parameter: range(2,6)
, which means values from 2 to 0 (but not including 6):
for x in range(2, 6):
print(x)
Else keyword in a for loop specifies a block of code to be executed when the loop has
ended:
for x in range(2, 6):
print(x)
else:
print(“Finally finished !”)
Nested Loops
adj = ["red", "big", "tasty"]
fruits = ["apple","banana", "cherry"]
for x in adj:
for y in fruits:
print(x,y)
While Loops:
We can execute a set of statements as long as a condition is true.
i=1
while i<6:
print(i)
i+=1
else:
print("i is no larger than 6")
Break & continue statement
i=1 i=0
While i<6: While i<6:
Print(i) i+=1
If i== 3: If i== 3:
Break continue
i+=1 Print(i)
If statement
a=331
b=33
if b>a:
print("b is greater than a")
elif a==b:
print("a and b are equal")
else:
print("a is greater than b")
Short Hand If
if a>b : print(“a is greater than b”)
Nested If
x= 13
if x>10:
print("above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20")