Section 2 Python
Section 2 Python
Section 2 Python
Started
Python Variables
Python Data Types
Python Numbers
Python Casting
Python Strings Agenda
Python Booleans
Python Operators
Python If...Else
Python Variables
“Creating Variables ”
Variables are containers for storing data values.
Unlike other programming languages, Python has no command for
declaring a variable.
A variable is created the moment you first assign a value to it.
Example
“Creating Variables ”
Variables do not need to be declared with any particular type, and can
even change type after they have been set.
Example
And you can assign the same value to multiple variables in one line:
Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
You can also use the + character to add a variable to another variable:
Output Variables
For numbers, the + character works as a mathematical operator:
If you try to combine a string and a number, Python will give you an Error
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
Create a variable outside of a function, and use it inside the function
Global Variables
If you create a variable with the same name inside a function, this
variable will be local, and can only be used inside the function. The
global variable with the same name will remain as it was, global and
with the original value.
The global Keyword
Normally, when you create a variable inside a function, that variable
is local, and can only be used inside that function.
To create a global variable inside a function, you can use the global
keyword.
Example
If you use the global keyword, the variable belongs to the global
scope:
The global Keyword
Also, use the global keyword if you want to change a global variable
inside a function.
Example
To change the value of a global variable inside a function, refer to
the variable by using the global keyword:
Identify Variable Type
Python allows you to identify type of the variable by using type() in
one line:
Python Data
Types
Built-in Data Types
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:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Setting the Data Type
In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = True bool
x = b"Hello" bytes
Python Numbers
String Literals
There are three numeric types in Python:
1. int
2. float
3. complex
Variables of numeric types are created when you assign a value to
them:
To verify the type of any object in Python, use the type() function:
Python Numbers
Int float Complex
int, or integer, is a whole number, Float, or "floating Complex numbers are
positive or negative, without point number" is a written with a "j" as
decimals, of unlimited length. number, positive or the imaginary part:
negative, containing
one or more decimals.
Type Conversion
You can convert from one type to another with the int(), float(), and
complex() methods:
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:
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This
can be done with casting. Python is an object-orientated language, and as
such it uses classes to define data types, including its primitive types.
Casting in python is therefore done using constructor functions:
1. int() - constructs an integer number from an integer literal, a float literal
(by rounding down to the previous whole number), or a string literal
2. float() - constructs a float number from an integer literal, a float literal
or a string literal (providing the string represents a float or an integer)
3. str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
Specify a Variable Type
Python String
String Literals
String literals in python are surrounded by either single quotation
marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
Get the characters from position 2 to position 5 ( 5 not included):
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters from position 5 to position 1 (-2 t -5 and -5 not
included), starting the count from the end of the string:
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
String Methods
The strip() method removes any whitespace from the beginning or the end
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“
The lower() method returns the string in lower case
print(a.lower()) # returns “hello, world!“
The upper() method returns the string in upper case
print(a.upper()) # returns “HELLO, WORLD! “
The replace() method replaces a string with another string:
print(a.replace("H", "J")) # returns “JELLO, WORLD! “
The split() method splits the string into substrings if it finds instances of the separator:
print(a.split(",")) # returns ['Hello', ' World!']
Check String
To check if a certain phrase or character is present in a string, we
can use the keywords in or not in.
Example
Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in
the plain"
x = "ain" in txt
print(x) # returns True
txt = "The rain in Spain stays mainly in
the plain"
x = "ain" not in txt
print(x)
String Concatenation
a = "Hello" a = "Hello"
b = "World" b = "World"
c = a + b Or c = a + " " + b
print(c) print(c)
age = 36
txt = "My name is John, I am " + age
Error print(txt)
quantity = 3
itemno = 567
Correct price = 49.95
myorder = "I want to pay {2} dollars for
{0} pieces of item {1}."
print(myorder.format(quantity, itemno,
price))
Python Booleans
Boolean Values
You can evaluate any expression in Python, and get one of two
answers, True or False.
Binary
Operatio
n
2.Python Assignment Example
3.Python Comparison Operators
3.Python Comparison Example
4.Python Logical Operators
4.Python Logical Example
5.Python Membership Operators
Membership operators are used to test if a sequence is presented in
an object:
5.Python Membership Example
6. Python Identity Operators
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:
6.Python Identity Example
6.Python Identity Example
7.Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Python
If...Else
Python If...Else
Python supports the usual logical conditions from mathematics:
• 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.
An "if statement" is written by using the if keyword.
Example
If statement:
Python If...
Python supports the usual logical conditions from mathematics:
• 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.
An "if statement" is written by using the if keyword.
Example
If statement:
Python If...elif
Python If...elif.. Else
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")
Python If...elif.. Else
Write a program to check whether a given number is even or odd
Python If...elif.. Else
Write a program to calculate the grade of a student according to :
If marks >= 90 the grade is A+
If marks < 90 and marks >= 80 the grade is A
If marks < 80 and marks >= 70 the grade is B
If marks < 70 and marks >= 60 the grade is B+
If marks < 60 and marks >= 50 the grade is C
If marks < the grade is F
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Python While Loops
Python For Loops
Thanks!
Any questions?