PYTHON PROGRAMMING
SYED JANI BASHA
CONTENTS
• PYTHON INTRODUCTION
• FEATURES OF PYTHON
• WHERE WE USE PYTHON
• HISTORY OF PYTHON
• SETTING UP PYTHON
ENVIRONMENT
• PROGRAM DEVELOPMENT CYCLE
• INPUT PROCESSING OUTPUT
Python is the world's most popular and fastest-growing computer
programming language. It is a multi-purpose and high-level programming
language. Python was invented by Guido Van Rossum in the year 1989, but it
was introduced into the market on 20th February 1991.
INTRODUCTION
Python Features
• Python is easy to learn and easy to understand.
• The Python is an interpreted programming
language. It executes the code line by line.
• The Python is a cross-platform programming
language. It can be used with any operating system
like Windows, Linux, MAC OS, etc.
• The Python is a free and open-source programming
language.
• The Python is an Object-Oriented, Procedural and
Functional programming language
• The Python is a multi-purpose programming
language
• The Python is a high-level programming language
• Python has a huge Community to get help all over
the globe.
• Python has a large Ecosystem of Libraries,
Frameworks, and Tools to work with it.
Cont………
Where we use the Python
• Data analysis
• Artificial intelligence / Machine learning
• Mobile Apps
• Desktop Apps
• Web Apps
• Automation
• Hacking
• Testing and more...
History of the Python
Latest version available is 3.8.5
Setting up Python Environment
In the above screen click on the Download Python 3.7.3 to start downloading
the installer for Windows operating system.
Make sure that “Add Python 3.7 to PATH” which is at bottom is checked and
click on “Install Now” to start the installation.
Then windows operating system shows a pop-up window to ask admin
permission to install the Python. Then click on Yes.
After clicking on Yes, windows start the installation of Python. The
installation screen seems like follows.
After completing installation Windows operating system displays the
following, saying that installation was successful. It seems like the
following screen. Then click on ‘Close’ to complete the installation
process.
PYTHON PROGRAM DEVELOPMENT CYCLE
No compile or link steps
Python programs simply import
modules at runtime and use the
objects they contain.
Because of this, Python programs
run immediately after changes
are made.
Behind the Scenes: How Python Works
INPUT PROCESSING OUTPUT
Most useful programs accept inputs from some source,
process these inputs, and then finally output results to
some destination.
In terminal-based interactive programs, the input source
is the keyboard, and the output destination is the
terminal display.
The Python shell itself is such a program; its inputs are
Python expressions or statements. Its processing
evaluates these items. Its outputs are the results
displayed in the shell.
Python Programming
SYED JANI BASHA
Contents
• Keywords
• Displaying Output with the Print
Function
• Comments
• Variables
• Reading Input from the Keyboard
Python Keywords
Displaying Output with the Print Function
The simplest way to produce output is using the print()
function where you can pass zero or more expressions
separated by commas. This function converts the
expressions you pass into a string before writing to the
screen.
Ex-1: Print(“Hello world”)
Output:
>>>>Hello world
Cont………
Ex-2:
x=5 Print(“X=“,x)
Output:
X=5
Ex-3: print(‘datacamp’, ‘tutorial’ , ‘Python’)
Output:
datacamp
Tutorial
Python
Since the python print() function by default ends with newline.
Python has a predefined format if you use print(a_variable) then it
will go to next line automatically.
Cont…….. sep=’separator’ : (Optional) Specify how to
separate the objects, if there is more than
one.Default :’ ‘
Ex-4: Print(192,168,2,10,sep=“ . ”)
Output:
192.168.2.10
In this example the separator used as dot
operator
Output Formatting
There are several ways to present the output of a program,
data can be printed in a human-readable form, or written
to a file for future use. Sometimes user often wants more
control the formatting of output than simply printing
space-separated values
• Formatting output using String modulo operator(%) :
Ex-1:
# print integer and float value
print("Geeks : % 2d, Portal : % 5.2f" %(1, 05.333))
Output:
Geeks : 1, Portal : 5.33
# print integer value
print("Total students : % 3d, Boys : % 2d" %(240, 120))
# print octal value
print("% 7.3o"% (25))
# print exponential value
print("% 10.3E"% (356.08977))
Output:
Total students : 240, Boys : 12
031
3.561E+0
The first placeholder “%2d” is used for the first component of our tuple, i.e. the integer
1. The number will be printed with 2 characters. As 1 consists only of one digits, the
output is padded with 1 leading blanks.
The second one “%5.2f” is a format description for a float
number. Like other placeholders, it is introduced with the %
character. This is followed by the total number of digits the
string should contain.
This number includes the decimal point and all the digits, i.e.
before and after the decimal point.
Our float number 05.333 has to be formatted with 5
characters. The decimal part of the number or the precision is
set to 2, i.e. the number following the “.” in our placeholder.
Finally, the last character “f” of our placeholder stands for “float”.
• Formatting output using format method User use {} to mark where a variable will be substituted and can
provide detailed formatting directives, but user also needs to provide
the information to be formatted
Ex-1:
# using format() method print('I love {} for its "{}!"'.format(‘india', ‘diversity’))
Output:
I love india for its diversity!
Ex-2:
# using format() method and refering
# a position of the object
print('{0} and {1}'.format(‘India', ‘Diversity')) print('{1} and {0}'.format (‘India', ‘Diversity'))
Output:
India Diversity
Diversity India
Comments
Comments are the useful information that the developers
provide to make the reader understand the source code.
Single line comments :
1.Python single line comment starts with hashtag symbol
with no white spaces (#) and lasts till the end of the line.
2. If the comment exceeds one line then put a hashtag on
the next line and continue the comment.
Ex-:
#program to add two numbers
a, b = 1, 3 # Declaring two integers
sum = a + b # adding two integers
print(sum) # displaying the output
Multi-line string as comment :
Python multi-line comment is a piece of text enclosed in a
delimiter (""") on each end of the comment. Again there
should be no white space between delimiter (""").
Ex-:
"""
This would be a multiline comment in Python that
spans several lines and describes importance of Python in
Computer Science field … """ print(“Python programming")
Python Variables
A variable is a named memory where a programmer can store
data and retrieve for future use using the same name. In Python,
variables are created without specifying any data type.
Syntax
variable_name = value
Example:
roll_number = 101
print(f 'Student roll number is {roll_number}’)
Output:
Student roll number is 101
Declaring multiple variables in a single statement:
In Python, it is possible to define more than one variable using a single
statement. When multiple variables are created using a single statement,
the variables and their corresponding value must be separated with a
comma symbol
Example:
name, roll_number = ('Rama', 101)
print(f 'Student {name} roll number is {roll_number}’)
Output:
Student Rama roll number is 101
Displaying data type of a variable
The Python programming language provides a built-in function
type( ) to display the data type of a variable.
Example:
a = 105
print(type(a))
a = 10.66
print(type(a))
a = 'rama'
print(type(a))
Reading input from keyboard
Python provides us with two inbuilt functions to read the input from the
keyboard.
•input ( prompt )
•raw_input ( prompt ) It is used in older versions of python
input ( ) : This function first takes the input from the user and then evaluates
the expression, which means Python automatically identifies whether user
entered a string or a number or list
Example:
val = input("Enter your value: ")
print(val)
Output:
Enter your value:123
123
Taking multiple inputs from user in Python
In C++/C user can take multiple inputs in one line using scanf but in
Python user can take multiple value Using split() method
Syntax :
input().split(separator, maxsplit)
Example :
x, y = input("Enter a two value: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)
print()
# taking three inputs at a time
x, y, z = input("Enter a three value: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
print()
Python Programming
SYED JANI BASHA
Contents
Operators
Arithmetic Operators
Relational Operators
Assignment Operators
Logical Operators
Identity Operators
Membership Operators
Any All
Type conversions
Expressions
Operators
An operator is a symbol used to perform arithmetical and
logical operations. In other words, an operator can be defined
as a symbol used to manipulate the value of an operand. Here,
an operand is a value or variable on which the operator
performs its task. For example, '+' is a symbol used to perform
mathematical addition operation.
Types of Operators in Python
In Python, there is a rich set of operators, and they are
classified as follows.
• Arithmetic Operators ( +, -, *, /, %, **, // )
• Relational Operators ( <, <=, >, >=, ==, != )
• Assignment Operators ( =, +=, -=, *=, /=, %=, **=, //= )
• Logical Operators ( and, or, not )
• Identity Operators ( is, is not )
• Membership Operators ( in, not in )
• Bitwise Operators ( &, |, ^, ~, <<, >> )
Arithmetic Operators in Python
Examples :
Relational Operators in Python
Examples :
Assignment Operators in Python
Logical Operators in Python
Identity Operators in Python
is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Membership Operators in Python
Membership operators are used to test whether a value is
present in a sequence. Here the sequence may be String, List,
or Tuple.
Any All in Python
Any and All are two built ins provided in python used for
successive And/Or.
Any
Returns true if any of the items is True. It returns False if empty
or all are false. Any can be thought of as a sequence of OR
operations on the provided iterables.
All
Returns true if all of the items are True (or if the iterable is
empty). All can be thought of as a sequence of AND operations
on the provided iterables.
ANY ALL
Type Conversion or Casting
The process of converting a value from one data type to
another data type is called Typecasting or simply Casting.
Output
Output
Output
Expressions in python
Expressions in python is a statement that include
operators , operands, variables
a = 2
b = 3
d=20
c = a + b*d
print c
e = a * b + d-(a*b)
print d
Python Programming
Syed Jani Basha
Contents
Data Types
None
Numeric data Types
Sequence Types
Mapping Types
Set Types
Python Strings
Using Functions and Modules
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: Bool
None Data Type None
Built-in Data Types
In programming, data type is an important concept.
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:
‘None' data type in Python
In many programming languages, we use the value null to represent
nothing. 'None' is Python's equivalent of NULL value in other
programming languages. In Python, 'None' is the object which represents
nothing. When we want a value to hold nothing, we do assign it with value
'None'.
Example - Python code to illustrate 'None' data type
roll_number = None
print(type(roll_number))
Output: <class ‘NoneType’>
'Numeric' data type in Python
The Python programming language provides four numeric data
types. They are as follows.
•int - All the numbers without fraction part (Example - 10). For
int, there is no upper limit.
•float - All the numbers with a fraction part (Example - 10.5). It’s accurate up to 15 decimal places
•complex - All the numbers with real and imaginary parts
(Example - 5 + 10j).
•bool - boolean values True and False.
Example - Python code to illustrate 'Numeric' data type
a = 10
print(f"the value {a} is of type {type(a)}")
a = 10.5
print(f"the value {a} is of type {type(a)}")
a = 100 + 5j
print(f"the value {a} is of type {type(a)}")
a = False
print(f"the value {a} is of type {type(a)}")
Output:
the value 10 is of type <class 'int'>
the value 10.5 is of type <class 'float'>
the value (100+5j) is of type <class 'complex'>
the value False is of type <class 'bool'>
Sequence Data Types:
A Sequence is an ordered collection of items, indexed by positive
integers. It is a combination of mutable (a mutable variable is one, whose
value can be changed) and immutable (an immutable variable is one, whose
value can not be changed) data types. There are three types of sequence data
type available in Python, they are:
•Strings
•Lists
•Tuples
Strings in Python
A string is a sequence of characters. It can be declared in python
by using double quotes. Strings are immutable, i.e., they cannot
be changed.
Example:
# Assigning string to a variable
a = "This is a string"
print a
Example:
wish_1 = 'Good Morning' wish_2 = "Good Evening“
Output:
Print(wish_1)
Print(wish_2)
Accessing String Values
In Python, whenever a string data value has assigned to a variable, it is
organized as an array of characters. The Python provides a variety of
ways to access the string values. Let's consider the following string value.
Accessing a character from a String Values
wish = 'Good Morning'
print(wish[0])
Output:
G
Example:
wish = 'Good Morning'
print(wish[-2])
o/p:
n
Example:
wish = 'Good Morning'
print(wish[2:8]) # Accessing specified substring
print(wish[:8]) # Here default starting index is '0'
print(wish[2:]) # Here default Ending index is 'Last - (11)’
o/p:
od Mor
Good Mor
od Morning
Lists
It is also a sequence of values of any type. Values in the list are called
elements/items.
Lists are mutable and indexed/ordered. The list is enclosed in square
brackets [ ].
For example, [2, 6, 8, 3, 1] or ["Python", "Java", "C++"] are both lists.
A List is just a bunch of numbers or strings that are kept together inside the
square bracket, sequentially. Each element of the list can be accessed by using
it's index number.
Creating a list in Python
The general syntax for creating a list is as follows.
Syntax
list_name = [element_1, element_2, element_3, ...]
Example:
student_data = [1, 'Rama', '2nd Year', 'CSE', 85.80]
print(student_data)
O/P:
1, 'Rama', '2nd Year', 'CSE', 85.80
Adding Elements to a List:
Using append():Only one element at a time can be added to the list by using append()
method, for addition of multiple elements with the append() method, loops are used.
Using insert():append() method only works for addition of elements at the end of the
List, for addition of element at the desired position, insert() method is used. insert()
method requires two arguments(position, value).
Using extend(): this method is used to add multiple elements at the same time at the end
of the list.
Example: using append()
# Creating a List
List = [ ]
print("Initial blank List: ")
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three
elements: ")
print(List)
Output:
Initial blank List:
[ ]
List after Addition of Three
elements:
[1, 2, 4]
Example: using insert()
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, ‘Hello') print("\nList after performing Insert Operation: ")
print(List)
Output:
Initial List:
[1, 2, 3, 4]
List after performing
Insert Operation:
['Hello', 1, 2, 3, 12,4]
Example: using extend()
# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)
# Addition of multiple elements
# to the List at the end
# (using Extend Method)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
Output:
Initial List:
[1, 2, 3, 4]
List after performing Extend
Operation:
[1, 2, 3, 4, 8, 'Geeks', 'Always']
Accessing elements from the List
# Creating a List with
# the use of multiple values List = [“TeamA", "For", “TeamB"]
# accessing a element from the
# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List) List = [[‘TeamA', 'For'] , [‘TeamB']]
# accessing an element from the
# Multi-Dimensional List using
# index number
print("Acessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
Output:
Accessing a element from the list
TeamA
TeamB
Acessing a element from a Multi-Dimensional list
For
TeamB
Negative indexing
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
Output:
Accessing element using negative indexing
Geeks
For
Removing Elements from the List
Elements can be removed from the List by using built-in remove() function but an Error arises if element doesn’t exist in the set. # Creating a List
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)
# Removing elements from List
# using Remove() method
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
Output:
Intial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
Tuples
A tuple is a collection which is ordered and unchangeable(immutable).
In Python tuples are written with round brackets.
#Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
#Accessing elements from tuples
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
#negative indexing
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
#Range of indexes
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
#Once a tuple is created, you cannot add items to it. Tuples are
unchangeable.
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Output:
('apple', 'banana', 'cherry')
banana
cherry
('cherry', 'orange', 'kiwi')
Tuples are unchangeable, so you cannot remove items from it, but you can delete the
tuple completely:
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
Join Two Tuples
To join two or more tuples you can use the + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output:
('a', 'b', 'c', 1, 2, 3)
Sets:
A set is a collection which is unordered and unindexed. In Python sets
are written with curly brackets.
#Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Output:
{'apple', 'cherry', 'banana'}
Access Items from sets
You cannot access items in a set by referring to an index, since sets are unordered
the items has no index.
But you can loop through the set items using a for loop, or ask if a specified value
is present in a set, by using the in keyword.
Example:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
apple
cherry
banana
Once a set is created, you cannot change its items, but you can add new items.
Add Items
• To add one item to a set use the add() method.
• To add more than one item to a set use the update() method.
Example
#Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Output:
{'orange', 'apple', 'cherry', 'banana'}
Example:
Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
Output:
{'mango', 'cherry', 'banana', 'apple', 'grapes', 'orange'}
Remove Item To remove an item in a set, use the
remove(), or the discard() method.
Example:
Remove "banana" by using the
remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Output: {'apple', 'cherry’}
remove() raise an error if the item
does not exist
Remove "banana" by using the discard()
method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
x = thisset.pop() # It removes the last item
Print(x)
Print(thisset)
Output: {'apple', 'cherry’} {‘cherry’} {‘apple’}
If the item to remove does not exist, discard()
will NOT raise an error.
Join Two Sets
We can use the union() method that returns a new set containing all items
from both sets.
Example:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
Output:
{'c', 1, 2, 3, 'b', 'a'}
Python Functions A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by
parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example:
def my_function(fname):
print(fname + " Thereja")
my_function(“Reema")
my_function(“Tony")
my_function(“Kevin")
Output:
Reema Thereja
Tony Thereja
Kevin Thereja
Number of Arguments By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the
function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function(“Kevin", “Thereja")
Output:
Kevin Thereja
If you try to call the function with 1 or 3 arguments, you will get an error:
This function expects 2 arguments, but gets only 1:
Example
def my_function(fname, lname):
print(fname + " " + lname)
my_function(“Kevin")
TypeError: my_function() missing 1 required positional
argument: 'lname'
Arbitrary Arguments, *args If you do not know how many arguments that will be passed into your function, add a * before the
parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example:
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function(“Tony", "Tiffany", "Linus")
Output:
The youngest child is Linus
Keyword Arguments You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = “Tony", child2 = "Tiffany", child3 = "Linus")
Output:
The youngest child is Linus
The phrase Keyword Arguments are often shortened to kwargs in Python
documentations.
Arbitrary Keyword Arguments, **kwargs
If you do not know how many keyword arguments that will be passed into your function,
add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly:
Example:
If the number of keyword arguments is unknown, add a double ** before
the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = “Tony", lname = "Refenes")
Output:
His last name is Refenes
Default Parameter Value The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list,
dictionary etc.), and it will be treated as the same data type inside the
function.
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Output:
apple
banana
cherry
The pass Statement function definitions cannot be empty, but if you for
some reason have a function definition with no
content, put in the pass statement to avoid getting
an error.
Example
def myfunction():
pass
Return Values To let a function return a value, use the return
statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
15
25
45
Recursion
Python also accepts function recursion, which means a defined function
can call itself.
Example:
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Output:
21
Python Modules
A module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Create a Module:
To create a module just save the code you want in a file with the file extension .py:
Example:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import
statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Output:
Hello Jonathan
Variables in Module
The module can contain functions, as already described, but also
variables of all types (arrays, dictionaries, objects etc):
Example
#Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
#Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Output:36
Re-naming a Module
You can create an alias when you import a module, by using
the as keyword:
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)
Output:36
Import From Module
You can choose to import only parts from a module, by using the from
keyword.
Example
#The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
#Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
Output:36
Python Programming
Syed Jani Basha
Contents
Decision Structures
if
if-else
if-elif-else
Nested Decision structures
More on Strings methods
Python Conditions and If statements
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.
In python different decision statements are
If
If-else
If-elif-else
Nested if
If statement An "if statement" is written by using the if keyword.
Example
If statement:
a = 33
b = 200
if b > a:
print("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.
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Using if-else
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
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")
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")
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".
Short Hand If If you have only one statement to execute, you can put it on the same line as the if statement.
Example
One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else 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
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary
Operators, or Conditional Expressions.
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.")
The pass Statement
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
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:
a = "Hello, World!"
print(a.lower())
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Hello, World!
hello, world!
HELLO, WORLD!
The replace() method replaces a string with
another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Jello, World!
The split() method splits the string into substrings
if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
['Hello', ' World!']
String Concatenation
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
HelloWorld
String Format
age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them
in the string where the placeholders {} are:
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Python Programming
Syed Jani Basha
Contents
Repetition Structures
while loop
for loop
Calculating running total
Input validation loops
Nested loops
While Loops
With the while loop we can execute a set of statements as long as
a condition is true.
Example
#Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
Output:
1
2
3
4
5
Note:increment i value otherwise
loop continues for ever
Using break
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
Using else with while
#Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output:
1
2
3
4
5
i is no longer less than 6
Python For Loops
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:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use the
range() function,
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.
Using the range() function:
for x in range(6):
print(x)
0
1
2
3
4
5
for x in range(2, 6):
print(x)
Output:
2
3
4
5
#Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
output
2
5
8
11
14
17
20
23
26
29
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the
"outer loop": Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Calculating running totals
total=0 #accumulator
another_number_to_add=True
while another_number_to_add == True:
number=int(input('Enter a number:'))
total=total+number
answer=input('Want to add another
number?')
if answer == 'Y':
another_number_to_add=True
else:
another_number_to_add=False
print('Here is u r total:',total)
Output:
Enter a number:5
Want to add another number?Y
Enter a number:6
Want to add another number?Y
Enter a number:9
Want to add another number?N
Here is u r total: 20
#Another way
total=0
for number in [8,6,7,5,]:
total=total+number
print('Here is the total:',total)
Output:
26
Precise way
total=0
number_of_numbers=int(input('How many?')
for n in range(number_of_numbers):
number=int(input('Give the next number:'))
total=total+number
print('Here is Your total:',total)
How many?5
Give the next number:6
Give the next number:9
Give the next number:5
Give the next number:4
Give the next number:1
Here is Your total: 25
Validating Inputs:
When we accept user input we need to check that it is valid. This checks to
see that it is the sort of data we were expecting. There are two different wa
ys we can check whether data is valid.
Method 1: Use a flag variable. This will initially be set to False. If we
establish that we have the correct input then we set the flag to True. We
can now use the flag to determine what we do next (for instance, we might
repeat some code, or use the flag in an if statement).
Method 2: Use try/except. Here, we try to run a section of code. If it doesn’t work (for instance, we try to convert a string to a number, but it doesn’t contain a number) then we run the except block of code.
Types of validation:
Validation technique Meaning
Type check Checking the data type e.g. int, float etc.
Length check Checking the length of a string
Range check Checking if a number entered is between two numbers
while True:
try:
age = int(input('How old are you? '))
break
except ValueError:
print('Please enter a whole number')
print('Your age is: ' + str(age))
Example - A length check using a flag
isLongEnough = False
while not isLongEnough:
password = input('Enter password at least 5 characters: ')
if len(password) >= 5:
isLongEnough = True
else:
print('Password entered is too short')
print('Your password entered is: ' + password)
Example - A range and type check using a flag and exception
isTeenager = False
while not isTeenager:
try:
age = int(input('How old are you? '))
if age >= 13 and age <= 19:
isTeenager = True
except:
print('You must enter a valid number between 13 and 19')
print('You are a teenager aged ' + str(age))
Thank you
Top Related