Python Unit 1
Python Unit 1
1. INTRODUCTION TO PYTHON:
1.2. Applications:
Bit Torrent file sharing
Google search engine, Youtube
Intel, Cisco, HP, IBM
i–Robot
NASA
Structure of Python Program
The python code you write is compiled into python byte code, which creates
file with extension .pyc . The byte code compilation happened internally, and
almost completely hidden from developer. Compilation is simply a translation
step, and byte code is a lower-level, and platform-independent , representation
of your source code. Roughly, each of your source statements is translated into a
group of byte code instructions. This byte code translation is performed to speed
execution byte code can be run much quicker than the original source code
statements.
Python Syntax
Python Indentation
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common use is four, but it has
to be at least one.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
Example
Variables in Python:
x=5
y = "Hello, World!"
Comments
Comments start with a #, and Python will render the rest of the line as a comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Creating a Comment
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
Python Variables
Variables
Creating Variables
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Example
a=4
A = "Sally"
#A will not overwrite a
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Many Values to Multiple Variables
Example
output :
Orange
Banana
Cherry
Output Variables
Example
x = "Python is awesome"
print(x)
output :
Python is awesome
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known
as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
output:
Python is awesome
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
You can get the data type of any object by using the type() function:
Example
x=5
print(type(x))
output :
<class 'int'>
In Python, the data type is set when you assign a value to a variable:
x = 20 Int
x = 20.5 Float
x = 1j Complex
x = range(6) Range
x = True Bool
x = b"Hello" Bytes
x = bytearray(5) Bytearray
x = memoryview(bytes(5)) Memoryview
x = None NoneType
If you want to specify the data type, you can use the following constructor functions:
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Python Numbers
int
float
complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
output:
<class 'int'>
<class 'float'>
<class 'complex'>
Int
Example
Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
output:
<class 'int'>
<class 'int'>
<class 'int'>
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Example
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
output:
1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
Note: You cannot convert complex numbers into another number type.
Random Number
Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
output :
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal x == y
!= Not equal x != y
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the result is not(x < 5 and x <
true
Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
is not Returns True if both variables are not the same x is not y
object
not in Returns True if a sequence with the specified value is not x not in y
present in the object
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bi
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, a
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33,
and so we print to screen that "b is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
Example
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
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")
In this example a is greater than b, so the first condition is not true, also the elif condition is
not true, so we go to the else condition and print to screen that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
Example
If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:
Example
You can also have multiple else statements on the same line:
Example
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
The and keyword is a logical operator, and is used to combine conditional statements:
Example
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Nested If
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
# having an empty if statement like this, would raise an error without the pass statement
Python While Loops
Python Loops
while loops
for loops
With the while loop we can execute a set of statements as long as a condition is true.
Example
i=1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
With the else statement we can run a block of code once when the condition no longer is
true:
Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
Example
The for loop does not require an indexing variable to set beforehand.
Example
for x in "banana":
print(x)
With the break statement we can stop the loop before it has looped through all the items:
Example
Example
Exit the loop when x is "banana", but this time the break comes before the print:
With the continue statement we can stop the current iteration of the loop, and continue with
the next:
Example
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
for x in range(6):
print(x)
The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
Example
Example
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Nested Loops
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
for x in adj:
for y in fruits:
print(x, y)
The pass Statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass