Python for Non-Programmers
1 Introduction
Programming is way to “instruct the computer to perform various tasks”.
Just like we use Urdu or English to communicate with each other , we use a programming language like, C, C++, R or Python to communicate with computer.
Implies, a program is specific set of ordered operations/instruction for a computer to perform
1.1 Python
Python is a widely used general-purpose, high level programming language. It was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
It is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes.
It’s easy and simple to understand language which feels like reading simple English. This pseudo code nature of Python makes it easy to learn and understand for beginners. Python is a programming language that lets you work quickly and integrate systems more efficiently.
1.2 Features of Python
1.2.1 High Level Programming
A high-level language (HLL) is a programming language such as C, FORTRAN, or Pascal that enables a programmer to write programs that are more or less independent of a particular type of computer. Such languages are considered high-level because they are closer to human languages and further from machine languages.
In contrast, assembly languages are considered low-level because they are very close to machine languages.
1.2.2 Interpreted Vs Compiled
Every program is a set of instructions, whether it’s to add two numbers or send a request over the internet. Compilers and interpreters take human readable code and convert it to computer readable machine code.
In a compiled language, the target machine directly translates the program. In an interpreted language, the source code is not directly translated by the target machine. Instead, a different program, aka the interpreter, reads and executes the code.
1.2.3 Object Oriented Programming
- There are many **object-oriented** programming languages including **JavaScript, C++, Java, and Python**. These functions are defined within the class and perform some actions helpful to that specific type of object.
1.2.4 Expressive
Expressive means that it’s easy to write code that’s easy to understand, both for the compiler and for a human reader.
Two factors that make for expressiveness:
Intuitively readable constructs
Lack of boilerplate code
Example: Expressive Python Vs less Expressive Java equivalent.
1.3 General Errors and Debugging
Programming is a complex process, and because it is done by human beings, it often leads to errors. Programming errors are called bugs and the process of tracking them down and correcting them is called debugging.
Syntax Errors: Syntax refers to the structure of a program and the rules about that structure.
- Python is not so forgiving. If there is a single syntax error anywhere in your program, Python will display an error message and quit, and you will not be able to run your program. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, though, you will make fewer errors and find them faster.
Run-time Errors: Run-time refers to an error that takes place while executing a program.
As opposed to the compilation errors that occur during a program compilation, runtime errors occur only during the execution of the program. For example, insufficient memory can often trigger a run-time error. The Code that exploded a rocket
Semantic Errors: If there is a semantic error in a program, it will run successfully, in the sense that the computer will not generate any error messages, but it will not do the right thing. It will do something else. Specifically, it will do what you told it to do.
- The problem is that the program you wrote is not the program you wanted to write. The meaning of the program (its semantics) is wrong. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing.
Experimental Debugging: One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.
In some ways, debugging is like detective work. You are confronted with clues, and you have to infer the processes and events that led to the results you see. Its an Iterative Process.
1.4 Installing Python
You may download and install Python from here.
2 Modules, PIP and Comments
2.1 Modules
Modules refers to a file containing Python statements and definitions. A file containing a python code is called a module. We use modules to break down large programs into small manageable and organized file. In other words, a module is a file containing code written by someone else (usually) which can be imported and used in our program.
Built in Modules –> Pre installed in Python -> import module_name
- Some examples of built in modules are random, bdb, calendar, os etc.
External Modules –> Needs to be installed using PIP -> pip install package_name
- Some examples of external modules are Pandas, Matplotlib, NumPy etc.
2.2 Preferred Installer Program (PIP)
PIP is package manager for python packages. If you have Python version 3.4 or later, PIP is included by default. Whenever we wants to install a package we may write like:
PIP install package_name
2.4 Using Python as Calculator
We can use Python as a calculator by typing python + enter on the terminal. This will open Read Evaluate Print Loop (REPL) i.e. >>>.
2.5 Some Arithmetic Operators
Symbol | Functionality |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulo (yields remainder after division) |
// | Integer Division (truncates towards zero) |
** | Exponentiation |
2.5.1 Python Code with Output
5/4
1.25
5%4
1
5//4
1
5**4
625
2.6 Assignment Operators
Assignment operators are used in Python to assign values to variables.
Operator | Example | Equivalent |
---|---|---|
= | x=2 | x=2 |
+= | x+=2 | x=x+2 |
-= | x-=2 | x=x-2 |
*= | x*=2 | x=x*2 |
/= | x/=2 | x=x/2 |
%= | x%=2 | x=x%2 |
//= | x//=2 | x=x//2 |
**= | x**=2 | x=x**2 |
2.6.1 Example
Assignment can be done on more than one variable “simultaneously” on the same line like this:
=1,2
x,yprint(x,y)
1 2
=8
x+=2
xprint(x)
10
-=3
xprint(x)
7
%=3
xprint(x)
1
Mixing operators between numbers and strings is not supported.
#This will not work
=1,2
a,b="String"
cprint(a+b)
3
print(a+b+c)
Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: unsupported operand type(s) for +: 'int' and 'str'
Detailed traceback:
File "<string>", line 1, in <module>
2.7 Conditions / Comparison Operator
Python uses boolean logic to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Operator | Description | Example |
---|---|---|
== | If the values of two operands are equal, then the condition becomes true. | (a == b) is not true. |
!= | If values of two operands are not equal, then condition becomes true. | (a != b) is true. |
<> | If values of two operands are not equal, then condition becomes true. | (a <> b) is true. This is similar to != operator. |
> | If the value of left operand is greater than the value of right operand, then condition becomes true. | (a > b) is not true. |
< | If the value of left operand is less than the value of right operand, then condition becomes true. | (a < b) is true. |
>= | If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. | (a >= b) is not true. |
<= | If the value of left operand is less than or equal to the value of right operand, then condition becomes true. | (a <= b) is true. |
2.7.1 Example
=(7>4)
b=(7<4)
cprint(b)
True
print(c)
False
=5
xprint(x==5) # Prints out True
True
print(x==2) # prints out False
False
print(x>3) # Prints out True
True
Notice that variable assignment is done using a single equals operator “=”, whereas comparison between two variables is done using the double equals operator “==”.
2.8 Logical Operators
Operator | Description | Example/Syntax |
---|---|---|
and | Logical AND: True if both the operands are true | x and y |
or | Logical OR: True if either of the operands is true | x or y |
not | Logical NOT: True if operand is false | not x |
2.8.1 Example
= True
Bool1= False
Bool2print("THe value if Bool1 and Bool2 is: ", (Bool1 and Bool2))
THe value if Bool1 and Bool2 is: False
print("THe value if Bool1 or Bool2 is: ", (Bool1 or Bool2))
THe value if Bool1 or Bool2 is: True
print("THe value if not Bool1 is: ", (not Bool1))
THe value if not Bool1 is: False
print("THe value if not Bool2 is: ", (not Bool2))
THe value if not Bool2 is: True
2.9 The “in” Operator
The “in” operator could be used to check if a specific object exists within an iterable object container, such as list:
= "Ahmad"
name= ["Ahmad", "Nadeem"]
List print(name in List) # this print True as Ahmad is in the list
True
2.10 Input Function
In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string.
a = input(" Please enter your name: ")
print(a) # Try yourself
2.11 Glossary
- algorithm
-
A set of specific steps for solving a category of problems.
- bug
-
An error in a program.
- comment
-
Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program.
- debugging
-
The process of finding and removing any of the three kinds of programming errors.
- exception
-
Another name for a runtime error.
- formal language
-
Any one of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs; all programming languages are formal languages.
- high-level language
-
A programming language like Python that is designed to be easy for humans to read and write.
- immediate mode
-
A style of using Python where we type expressions at the command prompt, and the results are shown immediately. Contrast with script, and see the entry under Python shell.
- interpreter
-
The engine that executes your Python scripts or expressions.
- low-level language
-
A programming language that is designed to be easy for a computer to execute; also called machine language or assembly language.
- natural language
-
Any one of the languages that people speak that evolved naturally.
- object code
-
The output of the compiler after it translates the program.
- parse
-
To examine a program and analyze the syntactic structure.
- portability
-
A property of a program that can run on more than one kind of computer.
- print function
-
A function used in a program or script that causes the Python interpreter to display a value on its output device.
- problem solving
-
The process of formulating a problem, finding a solution, and expressing the solution.
- program
-
a sequence of instructions that specifies to a computer actions and computations to be performed.
- Python shell
-
An interactive user interface to the Python interpreter. The user of a Python shell types commands at the prompt (>>>), and presses the return key to send these commands immediately to the interpreter for processing. The word shell comes from Unix. In the PyScripter used in this RLE version of the book, the Interpreter Window is where we’d do the immediate mode interaction.
- runtime error
-
An error that does not occur until the program has started to execute but that prevents the program from continuing.
- script
-
A program stored in a file (usually one that will be interpreted).
- semantic error
-
An error in a program that makes it do something other than what the programmer intended.
- semantics
-
The meaning of a program.
- source code
-
A program in a high-level language before being compiled.
- syntax
-
The structure of a program.
- syntax error
-
An error in a program that makes it impossible to parse — and therefore impossible to interpret.
- token
-
One of the basic elements of the syntactic structure of a program, analogous to a word in a natural language.
2.12 Exercise
Write a program to print a multiple lines string in Python.
Using the Python interpreter, type 1 + 2 and then hit return. Python evaluates this expression, displays the result, and then shows another prompt. * is the multiplication operator, and ** is the exponentiation operator. Experiment by entering different expressions and recording what is displayed by the Python interpreter.
Type 1 2 and then hit return. Python tries to evaluate the expression, but it can’t because the expression is not syntactically legal. Instead, it shows the error message:
{python, error=TRUE, include=TRUE} #print(1 2)
In many cases, Python indicates where the syntax error occurred, but it is not always right, and it doesn’t give you much information about what is wrong. So, for the most part, the burden is on you to learn the syntax rules.
In this case, Python is complaining because there is no operator between the numbers.
Write a program to display a user entered word “Easy” followed by “Python is very” using input() function.
Type cheese without the quotation marks. This is a run-time error; specifically, it is a NameError, and even more specifically, it is an error because the name cheese is not defined.
Install an External Module named pandas.
Write a program to print the contents of a directory using os module. Hint: Search online for the function which does so i.e how do i list all files of a directory.
Perform some arithmetic using REPL.
Use comparison operators to find out whether a given variable ‘a’ is greater than ‘b’ or not. consider a=45 and b=35.
Write a program to find out average of two numbers entered by the user.
Write a program which accepts the radius of a circle from the user and compute the area.
How to find the reminder of a given number?
3 Variables and Data Types
3.1 Variable
A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.
Words | Explanation |
---|---|
Variable | Container to store a value |
Keywords (can’t be used a variable name) | Reserved Words in Python |
Identifiers | Class/Function/Variable Name |
3.1.1 Keywords
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
3.2 Variable Types in Python
Every value in Python has a datatype. Different data types in Python are Integers, Floating point numbers, Strings, Boolean, List, Tuple, Dictionary, etc. Variables in Python can be declared by any name or even alphabets like a, aa, abc, etc.
A variable name can contain alphabets, digits and underscores
A variable name can start with alphabets or an underscore
Variable name is case sensitive
A variable name can’t start with a number/digit
Spaces are not allowed in variable name
3.2.1 How to Declare and Use a Variable
Let see an example. We will define variable in Python and declare it as “a” and print it.
=10
aprint(a)
10
= 5 ,6
x , y print(x,y)
5 6
=c=d=30
bprint(b,c,d)
30 30 30
3.2.2 How to know the Type of a Variable
Python is completely object oriented, and not “statically typed”. You do not need to declare variables before using them, or declare their type, i.e. python automatically identify the type. Every variable in Python is an object.
Here are few basic types of variables. type() function is used to find out the type of a variable.
=10
aprint(type(a))
<class 'int'>
=10.1
bprint(type(b))
<class 'float'>
="State Bank of Pakistan"
cprint(type(c))
<class 'str'>
=True
dprint(type(d))
<class 'bool'>
=None
eprint(type(e))
<class 'NoneType'>
3.2.3 Re-declare a Variable
You can re-declare Python variables even after you have declared once.
#declare a variable and initialize it
=10
a# re-declaring the variable
="State Bank of Pakistan"
aprint(a)
State Bank of Pakistan
print("a"+10) # we can't concatenate string with integer
Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: can only concatenate str (not "int") to str
Detailed traceback:
File "<string>", line 1, in <module>
print("a" + "10")
a10
3.2.4 Type Casting
Type Casting is a process in which we convert a literal of one type to another. built-in functions int(), float() and str() shall be used for typecasting.
- int() can take a float or string literal as argument and returns a value of
class 'int'
type. - float() can take an int or string literal as argument and returns a value of
class 'float'
type. - str() can take a float or int literal as argument and returns a value of
class 'str'
type.
3.2.5 Type Casting int to float and string
=100 # an integer
nprint(type(n))
<class 'int'>
=float(n)
fprint(type(f))
<class 'float'>
=str(n)
sprint(type(s))
<class 'str'>
3.2.6 Type Casting float to int and string
=10.5 #a float
fprint(type(f))
<class 'float'>
=int(f)
nprint(type(n))
<class 'int'>
=str(f)
sprint(type(s))
<class 'str'>
3.3 Exercise
Guess the type of 6/2, 6//2 and check the results.
What is the value of x after the following is run:
x=4
x=x/2Create a variable named
carname
and assign the valuetoyota
to it.Assign: 3 to variable glass_of_water and printout the message “I drank 3 glasses of water today” by using variable name.
Let’s try to see what happens after assigning a new value to our variable. Note that program gets executed line by line.
glass_of_water=3
glass_of_water=glass_of_water + 1
print()
Check the type of the variable define above.
Type Cast the above variable first into float and then to string.
Define a variable a =3 and A=‘NIBAF’. Will ‘A’ overwrite ‘a’?
Check the type of a variable assigned using input() function.
Calculate square of the number entered by the user.
Write a program to accept two numbers from the user and calculate multiplication.
Display string “My”, ‘Name’, “Is”, “Python” as “My**Name**Is**Python” Hint: Default separator in print function is space i.e. ” “.
Write a program to take three names as input from a user in the single
input()
function call.Define a complex variable. 😎
4 Strings
A string is a sequence of characters. Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −
var1 = 'Hello World!'
var2 = "Python Programming"
var3 = '''Python Programming
for begginners'''
4.1 String Indexing
Individual characters of a string can be accessed directly using a numeric index.
String indexing in python is zero-based.
The first character in the string has index 0.
The next has index 1 . . . and so on.
The index of the last character will be length of the string minus 1.
4.1.1 Example
String | a | h | m | a | d |
---|---|---|---|---|---|
Index | 0 | 1 | 2 | 3 | 4 |
Negative Index | -5 | -4 | -3 | -2 | -1 |
4.2 Slicing Strings
You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon in \[ \], to return a part of the string. i.e. we can get a part of the string using slicing.
4.3 Syntax : \[Start : Stop : Step\]
Start: First Index of the sub-string you want to extract.
Stop: Last Index of the sub-string you want to extract.
Step: The size of the jump you want to take while extracting the subsection.
4.4 Scenarios
Scenario 1: No step size
Scenario 2: No stop index
Scenario 3: No start index
Scenario 4: No start and stop index
Scenario 5: No strat, step or stop index
Scenario 6: Single charachter as a string
4.4.1 Example
= "Welcome to the World of Python"
A print(A[3:7]) # by default step size is 1
come
print(A[24:]) # python will assume last index of string as the stop index
Python
print(A[:7]) #python assume the start index as 0
Welcome
print(A[::2]) # python will give every second chanracter from complete string
Wloet h ol fPto
print(A[::]) # start=0, stop=last index, step=1 by deafult
Welcome to the World of Python
print(A[0:1]) # [start:start+1:1]
W
Omitting both indices returns the original string, in its entirety. Literally. It’s not a copy, it’s a reference to the original string:
='NIBAF'
s= s[:]
t print(id(s))
1486119600
print(id(t))
1486119600
4.5 Concatenating the Strings
String concatenation means add strings together. Use the + character to add a variable to another variable:
= "Python Eats"
x = "???"
y= x+y
z print(z)
Python Eats???
4.6 String Functions
Function | Explanation | Syntax |
---|---|---|
capitalize() | The capitalize() method converts first character of a string to uppercase letter and lowercases all other characters, if any |
|
upper() | The upper() method converts all lowercase characters in a string into uppercase characters |
string.upper() |
lower() | The lower() method converts all uppercase characters in a string into lowercase characters |
string.lower() |
swapcase() | The swapcase method converts lower to uppar and upper to lower |
string.swapcase |
count() | The count() method returns the number of occurrences of a substring in the given string |
string.count() |
endswith() | The endswith() method returns True if a string ends with the specified suffix. If not, it returns False |
string.endswith() |
find() | The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1 |
string.find() |
len() | The len() method returns the length of a string |
string.len() |
index() | The index() method returns the index of first occurrence of the substring (if found). If not found, it returns substring not found |
string.index() |
replace() | The replace() method replaces each matching occurrence of the old character/text in the string with the new character/text |
string.replace() |
strip() | Removes leading and trailing characters from a string. | string.strip() |
lstrip() | Removes leading characters from a string. | string.lstrip() |
rstrip() | Removes trailing characters from a string. | string.rstrip() |
join() | Joins elements of an iterable into a single string. | string.join() |
split | Splits a string into a list of substrings based on separator | string.split() |
= " Python is Easy "
a = ":".join(["Ahmad", "Nadeem"])
b = "Ahmad Nadeem".split()
c print(a.upper())
PYTHON IS EASY
print(a.endswith('y'))
False
print(a.find('n'))
9
print(a.replace("Python" , "Jython"))
Jython is Easy
print(a.strip())
Python is Easy
print(b)
Ahmad:Nadeem
print(c)
['Ahmad', 'Nadeem']
4.7 Escape Sequence Characters
In Python, escape sequences are indicated by a backslash ( \ ).
Syntax | Explanation |
---|---|
\n | The most important one may be \n which indicates a new line. Like so, multiple logical lines can be stacked into a single physical line. |
\’ | Another escape sequence worth mentioning is \' for a single quote within a string. |
\\ | A backslash also escapes itself so if it’s really a backslash you want, double it as in \\ . |
\t | insert a tab in a string |
4.8 Formatted String Literal or f-string
= 5
n = 10
m = n*m
prod print('The product of', n, 'and', m, 'is', prod)
# this can be reproduced by using f-string as:
The product of 5 and 10 is 50
print(f'The product of {n} and {m} is {prod}')
The product of 5 and 10 is 50
4.9 Exercise
Convert the String
"welcome to the beautiful world of python"
to"Welcome To The Beautiful World Of Python"
Find the output of the following:
str1 = "PYnative" print(str1[1:4], str1[:5], str1[4:], str1[0:-1], str1[:-1])
Guess the output of the following:
# print('python \n cpython') # print('python \t cpython') # print('python \\ cpython')
if a=‘1’ and b=‘2’ what will be the value of c=a+b?
Consider the variable g, and find the first index of the sub-string snow:
g = “Mary had a little lamb Little lamb, little lamb Mary had a little lamb \ Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \ Everywhere that Mary went The lamb was sure to go”
In the above variable g, replace the sub-string Mary with Bob:
What is the result of following?
“hello Mike”.find(“Mike”)If string=‘Welcome’ then how to get output as WelcomeWelcomeWelcome?
Ask the name and favorite fruit from two persons using input and return as a single string. like: Ahmad likes Mangoes and Muhammad likes Oranges.
Write a program to detect double spaces in a string.
Replace the double spaces in above question with a single space.
Write a program to format the following letter using escape sequence characters.
letter = ” Dear Participants, This Python course is nice. Thanks!”
Find the length of the word NIBAF.
Print the reversed str = ‘NIBAF’
Attempt to index beyond the end of the string results and checkout the result. like ,‘Ahmad\[6\]’
Select the every third letter from the str = ‘I am learning python’
How to check the given word, sentence or a number is palindrome!
A word, verse, or sentence (such as ‘Able was I ere I saw Elba’) or a number (such as 1881) that reads the same backward or forward is called palindrome.
Write a program which accepts the user’s first and last name then print in reverse order.
Write a program to accept a filename from user and print the name and extension of that file.
5 Lists and Tuples
List is one of the most powerful data structures in Python. The List data type is made with so much of efforts and every programmer from beginner, intermediate to an expert should understand how it works.
Lists are mutable collection of objects. i.e. they are container to store a set of values of any data type.
for example:
= [ 'milk', 'cars', 14, False] myList
Lists are ordered. We can index them and access values.
Lists are heterogeneous. A list can contain different types of elements.
Lists are mutable. You can change values in them.
5.1 Creating a Lists
= [1,2,3]
items = list('123')
items1 =['123']
items2=[]
items37)
items3.append(8) # adds at the end of the list
items2.append(=[1, 2, False, [4,5]]
items4print(items, items1, items2, items3, items4)
[1, 2, 3] ['1', '2', '3'] ['123', 8] [7] [1, 2, False, [4, 5]]
5.1.1 Indexing and Slicing Lists
= ['milk', 'cars', 14, False]
myList 0] myList[
'milk'
-1] myList[
False
0::2] myList[
['milk', 14]
5.1.2 Modifying Lists
Unlike strings, lists are mutable. Its values can be changed.
= ['milk', 'cars', 14, False]
myList 1] = 'Trucks'
myList[ myList
['milk', 'Trucks', 14, False]
2,9)
myList.insert( myList
['milk', 'Trucks', 9, 14, False]
5.2 Sorting List
The list.sort()
method sorts the elements of a list in ascending or descending order:
= [4,1,2,7,5,3]
a
a.sort()print(a)
[1, 2, 3, 4, 5, 7]
=True)
a.sort(reverseprint(a)
[7, 5, 4, 3, 2, 1]
5.2.1 Sorting using a key parameters:
= ['Karachi', 'Lahore', 'Faisalabad', 'Hayderababd']
cities =len)
cities.sort(keyprint(cities)
['Lahore', 'Karachi', 'Faisalabad', 'Hayderababd']
=len, reverse=True)
cities.sort(keyprint(cities)
['Hayderababd', 'Faisalabad', 'Karachi', 'Lahore']
5.2.2 Removing Elements from the list
= ['Karachi', 'Lahore', 'Faisalabad', 'Hayderababd']
cities 0) # will delete the value at index 0 an return its value cities.pop(
'Karachi'
cities
['Lahore', 'Faisalabad', 'Hayderababd']
'Lahore')
cities.remove( cities
['Faisalabad', 'Hayderababd']
= cities.copy() #create a copy of list cities2
5.3 Converting a String to a List
String can be convert to a list, as per spaces ” ” or any other special characters “_”, according to the users choice, are encountered. To do this we use the split() method.
5.3.1 Syntax
string.split('delimiter')
= "I like Python"
string print(string.split(" "))
['I', 'like', 'Python']
= "I_Like_Python"
string1 print(string1.split("_"))
['I', 'Like', 'Python']
5.4 Tuples
Tuples are collections of Python objects. They are similar to lists but the difference between them is that tuples are immutable while lists are mutable. Tuples are created by typing a sequence of items, separated by commas. Optionally, you can put the comma-separated values in parenthesis.
Tuple1=(1,2,5,6)
Tuple2=(‘a’, “b”, ‘c’, “d”)
Tuple3 = () #empty tuple
Tuple4 = 5,3,1
Tuple5 = (“London”, “Tokyo”, “Korea”, 1986, 1640, 1948)
Note: To create a single item tuple, you have to use a comma after the value.
= (5) # its not a tuple
Tup1 = (5,)
Tup2 = ("London", "Tokyo", "Korea", 1986, 1640, 1948)
Tuple5 print(type(Tup1))
<class 'int'>
print(type(Tup2))
<class 'tuple'>
print(Tuple5.index("Korea"))
2
The values of tuples are stored at different index positions starting from zero. We can access the values by using their index positions inside square brackets. We can index or slice tuples like lists.
= (1, 2, 2, 1, 3, 1, 4,2)
a
print(a[0]) , print(a[4])
1
3
(None, None)
print(a.count(2)) # will return the number of times 2 occurs
3
print(a.index( 2)) # will return the index of first occurrence of 2
1
5.5 Tuple Unpacking
With a special syntax, Python can unpack the values of a tuple and extract them into single variables.
= (1,2,3)
a,b,c print(a)
1
print(b)
2
print(c)
#or
3
= (4,5,6)
coordinates = coordinates # same can be used to unpack a list
x,y,z print(x)
4
The number of variables to the left and right side should be the same and it assigns each variable respectively.
5.6 Lists Vs Tuples
5.6.1 Methods Available for List:
list = [2,3,5,7,11,13,17]
print(dir(list))
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
5.6.2 Methods Available for Tuple:
tuple = (1,4,9,16,25,36)
print(dir(tuple))
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
As we observe that list have more methods as compare with tuples, but this extra functionality comes at a price i.e. list occupy more memoray than tuple. let’s have a look:
import sys
print(help(sys.getsizeof))
Help on built-in function getsizeof in module sys:
getsizeof(...)
getsizeof(object [, default]) -> int
Return the size of object in bytes.
None
list = [1,2,3,4,5,6,7]
tuple = (1,2,3,4,5,6,7)
print("The Size of the List is", sys.getsizeof(list ), 'bytes')
The Size of the List is 120 bytes
print("The Size of the Tuple is", sys.getsizeof(tuple), 'bytes')
The Size of the Tuple is 96 bytes
when working with big data, this can be significant.
List | Tuples |
---|---|
|
|
|
|
|
|
let’s have a look that how tuples are more efficient than lists:
time required to create 1000,000 lists and tuples of same size.
import timeit
= timeit.timeit(stmt="[1,2,3,4,5,6]", number=1000_000)
list_test = timeit.timeit(stmt="(1,2,3,4,5,6)", number=1000_000)
tuple_test print('Time needed to make 1000000 lists: ', list_test)
Time needed to make 1000000 lists: 0.06933149999531452
print('Time needed to make 1000000 tuples: ', tuple_test)
Time needed to make 1000000 tuples: 0.013147399993613362
5.7 Exercise
Create a list
a_list
, with the following elements1
,hello
,[1,2,3]
andTrue
.Find the first and last value of the list.
Find the value stored at index 1 of
a_list
.Retrieve the elements stored at index 1, 2 and 3 of
a_list
.Concatenate the following lists
A = [1, 'a']
andB = [2, 1, 'd']
Make the list of the PIN of 5 officers and sort them in ascending and descending order.
Consider the following tuple and Find the length of the tuple,
genres_tuple
genres_tuple = (“pop”, “rock”, “soul”, “hard rock”, “soft rock”, “R&B”, “progressive rock”, “disco”)Access the element, with respect to index 3.
Use slicing to obtain indexes 3, 4 and 5.
Find the index of
"disco".
Generate a sorted List from the Tuple
C_tuple=(-5, 1, -3).
Check that a python tuple can’t be altered.
Find the sum of
list2 = [1,2,3,4]
.Write a program to count the number of occurrences of 4 in
tuple1=(4,1,2,5,7,4,8,4,4)
Reverse a list2 define above (Q.13) using index method.
Make the list of the words of “I am doing well”
sort the above created list as per length of the words in reverse order.
list1 =
[100, 200, 300, 400, 500]
, output =[500,400,300,200,100]
list2 =
[10, 20, [300, 400, [5000, 6000], 500], 30, 40]
, Expected output :[10, 20, [300, 400, [5000, 6000, 7000], 500], 30, 40]
list1 =
["a", "b", ["c", ["d", "e", ["f", "g"], "k"], "l"], "m", "n"]
# sub list to addsub_list = ["h", "i", "j"]
Expected Output:["a", "b", ["c", ["d", "e", ["f", "g","h","i","j"], "k"], "l"], "m", "n"]
list1 =
[5, 10, 15, 20, 25, 50, 20]
Expected Output:[5, 10, 15, 200, 25, 50, 20]
list1 =
[5, 20, 15, 200, 25, 50, 220]
remove 20 from the list.
6 Python Dictionaries and Sets
6.1 Dictionaries
Like a real-life dictionary has words and meanings, Python dictionaries have keys and values. Dictionaries in Python are collections that are unordered, indexed and mutable. They hold keys and values.
They are in curly brackets. Key-value pairs are separated by commas and keys and values are separated by colons. Keys in dictionaries are unique and immutable. You can search for a value if you know the key. One key cannot have two values.
= {"Key": "Value", "Key": "Value1", "SBP" : "State Bank of Pakistab", "BSC" : "Banking Services Corporation", "PSPC" : "Pakistan Security Printing Corporation", "NIBAF" : "National Institute of Banking and Finance", 'Marks' : [71, 78, 84]}
Financial_Dictionary print(type(Financial_Dictionary))
<class 'dict'>
print(Financial_Dictionary)
{'Key': 'Value1', 'SBP': 'State Bank of Pakistab', 'BSC': 'Banking Services Corporation', 'PSPC': 'Pakistan Security Printing Corporation', 'NIBAF': 'National Institute of Banking and Finance', 'Marks': [71, 78, 84]}
print(Financial_Dictionary['Marks'])
[71, 78, 84]
del(Financial_Dictionary['BSC']) # will del key=BSC
print(Financial_Dictionary)
{'Key': 'Value1', 'SBP': 'State Bank of Pakistab', 'PSPC': 'Pakistan Security Printing Corporation', 'NIBAF': 'National Institute of Banking and Finance', 'Marks': [71, 78, 84]}
print('BSC' in Financial_Dictionary) # as it already deleted , Results in False
False
6.2 Nested Dictionaries and Dictionary Methods
= {'1' : 'One', '2':'Two', "Dict1" : {'3': 'Three', '4' : 'Four'} }
Dict print(Dict['1'])
One
print(Dict['Dict1']['4'])
Four
'1'] = 'i' # Immutable i.e. we can change
Dict[print(Dict)
{'1': 'i', '2': 'Two', 'Dict1': {'3': 'Three', '4': 'Four'}}
print(Dict.keys()) # will show the keys of a dictionary
dict_keys(['1', '2', 'Dict1'])
print(Dict.values()) #will show the value of a dictionary
dict_values(['i', 'Two', {'3': 'Three', '4': 'Four'}])
print(Dict.items()) # print the (key : value) for all contents of Dictionary
dict_items([('1', 'i'), ('2', 'Two'), ('Dict1', {'3': 'Three', '4': 'Four'})])
= {'Hello' : 'World'}
new_dict # will append new_dict in Dict
Dict.update(new_dict) print(Dict)
{'1': 'i', '2': 'Two', 'Dict1': {'3': 'Three', '4': 'Four'}, 'Hello': 'World'}
print(Dict['9']) # returns error if not in Dict
Error in py_call_impl(callable, dots$args, dots$keywords): KeyError: '9'
Detailed traceback:
File "<string>", line 1, in <module>
print(Dict.get('9')) # return None
None
Quick Quiz: Write a program to ask a phone number in digits and translate them like: 123 One Two Three.
Solution! (Click for Solution)
# Phone = input ("Number Please: ")
= "123"
phone = {
Digit_Dict "1" : "One",
"2" : "Two",
"3" : "Three",
"4" : "Four"
}= ""
output for numbers in phone:
+= Digit_Dict.get(numbers, "!") + " "
output print(output)
One Two Three
Quick Quiz: Get a message from input method and resturn the same message with translated emoji like “:)” to 😊.
#message = input(">")
= "I am happy :)"
message = message.split()
words # print(words)
= {
emoji_dict ":)" : "😊",
":(" : "😒"
}= ""
trans_message for word in words:
+= emoji_dict.get(word, word)+ " "
trans_message print(trans_message)
I am happy 😊
6.3 Sets
Sets in Python are a collection of unordered and unindexed Python objects. Sets are mutable, iterable and they do not contain duplicate values. It is similar to the concept of the mathematical set. That is, set is a collection of non-repetitive elements. The elements in a set are declared inside curly braces separated by commas.
= {2,1,3,4,2,5,6,3,8}
a type(a)
<class 'set'>
print(a)
{1, 2, 3, 4, 5, 6, 8}
= {} # check the type of a
b = set() # an empty set
c type(c)
<class 'set'>
2)
c.add (5)
c.add (print(c)
{2, 5}
Since the sets are unindexed, we cannot use slicing or indexing on sets, it will give us a TypeError error when using indexing.
6.3.1 Properties of Sets
Sets are Unordered
Sets are Unindexed
There is no way to change items in a set
Sets can’t contain duplicate values
6.4 Operations on Sets
Col1 | Col2 |
---|---|
set.add( n) | The add() function in python sets takes the value as an argument which we want to add to our set and adds the element in our set. one element at a time |
set. remove ( m ) | The function deletes the specified element from the set and if the element is not present in the set, it does not return any error. |
set. pop ( ) | pop() function doesn’t take any argument and it removes an arbitrary element from the set and also returns the deleted element. |
set. clear( ) | The clear() function empties the set. It can also be used for dictionaries. |
set.update( ) | The update() function in python sets can be used to add multiple values to the set at once. It takes an iterable like lists, set or tuple as an argument. |
set.union ({4,5}) | Return a new set with all item from both sets |
set.intersection({7,8}) | Return a set contains common item of both sets |
set1.difference(set2) | Return the Set1 - Set2 |
set1.symmetric_difference(set2) | return the elements those are not common in set1 and set2 |
set1.issubset(set2) |
= {1,2,3}
c 1,2,3]) # we can't add list and dictionaries in a set c.add([
Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: unhashable type: 'list'
Detailed traceback:
File "<string>", line 1, in <module>
1,2,3))# we can add tuple
c.add((print(c)
{1, 2, 3, (1, 2, 3)}
print(len(c)) # prints the length of set c
4
2) # removes 2 from set c
c.remove(print(c)
{1, 3, (1, 2, 3)}
print(c.pop()) # removes any arbitrary number from set c and return the value
1
print(c)
{3, (1, 2, 3)}
8,9})
c.update({print(c)
{3, 8, 9, (1, 2, 3)}
6.5 Exercise
The Swift, City and Civic have the following prices in thousands 2800, 3500, 6200 respectively. Create a dictionary
car_price_dict
where the keys are the car name and the price in thousands are the values.You will need this dictionary for the next two questions: Dict= {‘SBP_ACT’: ‘1956’, ‘BCO’:‘1962’}
In the Dict, what are the keys?
In the Dict, what are the values?
Use the dictionary find the price of the City.
Find the names of the cars from the dictionary using the method
keys()
Find the prices of the cars from the dictionary using the method
values()
Create a dictionary of Urdu words with values as their English translation. Provide user an option to look it up.
Consider the list
A = [1, 2, 2, 1]
and setB = set([1, 2, 2, 1])
, doessum(A) == sum(B)
?Create a new set
C
that is the union of setsA={1, 2, 3, 4}
andB={3, 4, 5, 6}
.Find out if
A
is a subset ofC.
Write a program to add an element in a set.
Write a program to add more than one element in a set.
Write a program to remove items from a given set.
Write a program to create an intersection of set.
Write a program to create a union of sets.
Write a program to input 5 numbers from the user and display all the unique numbers
Can we have a set with elements 3 and ‘3’ ?
What is the type of s = { }?
What will be the length of set s:
s = set(), s.add(1), s.add(1.0), s.add(‘1’)
Create a dictionary. Allow 4 users to enter their favorite Fruits as value , ans use their names as keys. Assume names are unique.
If names of 2 users are same in above problem, what will happen?
If fruit options of 2 users are same in above problem, what will happen?
Check if a set is a subset of another set using comparison operator and isubset() operator.
Write a Python program to print out a set containing all the colors from color1 which are not present in color2.
color1 = set(["White","Black", "Red"])
color2 = set(["Red", "Green"]), Expected Output:{'Black','White'}
Provide a use case for each of the following Python data structures: tuple, list, and dictionary. Explain why each use case is appropriate for each data structure as opposed to the others.
List - A shopping list. The list type is appropriate, since it can be changed.
Tuple - The first 7 prime numbers. A tuple is a suitable structure, because it is a immutable data type.
Dictionary - A list of words and their meanings. Since a dictionary is made up by key-value pairs, the key would be the word and the value would assume it’s meaning.
Set - A list of registered e-mails in a system. It’s a proper way to store them, for the e-mails must each be unique.
Ask the phone number from a user, and convert integers into strings like: 1 to one.
Creat a dictionary of animal names as keys and their pictures as values. Hint: to get picture/emoji’s press window+period(.)
Take input from user to show the picture of the animal. Also provide to look at the names of the animals in the dictionary.
If animal’s picture is not in the dictionary, provide the option to add the name and picture in the dictionary on run time.
7 Conditional Expressions
Decision making is required when we want to execute a code only if a certain condition is satisfied. The if…elif…else statement is used in Python for decision making. If-else conditional statement is used in when a situation leads to two conditions and one of them should hold true.
7.1 If else Statement Syntax
=1
xif x==1:
print("x is 1") # this is body of if or statement
#else:
# print("x is not 1") # this is body of elif
x is 1
Here, the program evaluates the test expression
and will execute statement(s) only if the test expression is True
. If the test expression is False
, the statement(s) is not executed.
In Python, the body of the if
statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
Remember: Python interprets non-zero values as True
. None
and 0
are interpreted as False
.
7.2 Indentation
Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces. For example:
=1
xif x==1:
#indented four spaces
print("x is 1")
else:
print("x is not 1")
x is 1
If statement, without indentation (will raise an error).
7.3 If elif and else Statement
=-1
xif x==1:
#indented four spaces
print("x is 1") # this is body of if or statement
elif x<0:
print("x is less than zero")
else:
print("x is not 1") # this is body of elif
x is less than zero
7.3.1 Example
Write a program to print ‘Yes’ when the number entered by the user is greater than or equal to 25.
#n = int(input(" Please enter the number: "))
=32
nif n>=25:
print("Yes")
else:
print("No")
Yes
Write a program to check if a number entered by the user is positive or negative or zero and display an appropriate message.
#n = int(input(" Please enter the number: "))
= -4
n if n>0:
print("Number is +ve")
elif n==0:
print("Number is zero")
else:
print("Number is -ve")
Number is -ve
we use if elif and else statement if one of the statement is true.
7.4 Nested if statements
We can have a if...elif...else
statement inside another if...elif...else
statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.
Example: Write a program to check if a number entered by the user is positive or negative or zero and display an appropriate message using nested if statement.
#n = int(input(" Please enter the number: "))
= 3
n if n>=0:
if n==0:
print("Number is zero")
else:
print("Number is +ve")
else:
print("Number is -ve")
Number is +ve
7.4.1 Note:
There can any number of elif statements.
last else will be executed if all elif conditions/statements fails.
7.5 Multiple If Conditions
7.5.1 Example
Write a program to print largest number among four numbers entered by the user.
= 4 #n1 = int(input(" Enter the First Number : "))
n1 = 3 #n2 = int(input(" Enter the 2nd Number : "))
n2 = 2 #n3 = int(input(" Enter the 3rd Number : "))
n3 = 1 #n4 = int(input(" Enter the 4th Number : "))
n4
if n1>n2:
= n1
f1 else:
= n2
f1 if n3>n4:
= n3
f2 else:
= n4
f2 if f1>f2:
print(f" The Largest Number is : {f1} ")
else:
print(f" The Largest Number is : {f2} ")
The Largest Number is : 4
7.6 Exercise
Write a program to check whether a user entered number is odd or even?
Take two numbers from user and print larger.
Take three numbers from user, and print the largest.
Write a program to check whether a user entered number is odd or even,valid only for first 10 natural numbers.
write a program to get the difference b/w a given number and 17, if number is greater than 17, return double the absolute difference.
Write a program to calculate the sum of three given numbers, if values are equal then return thrice of their sum.
Write a prog. to get a new string from a given string where “Is” has been added to the front. if the given string already begins with “Is” then return the string.
If Question mark ‘?’ is missing in above string, then also include the ‘?’ at the end.
Write a program to find out whether a given post is talking about “SBP” or not.
- Write a program to find out whether a student is fail or pass? if it require total 40% and at-least 33% in each subject to pass. Assume 3 subjects, input from the user and marks are out of 100.
Write a program to detect a spam (OSICO Spam detector), a spam comment is defined as a text containing following keywords:
“make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program to detect these spams.
Write a program to calculate the grade of an officer from his numeric rating from the following scheme: greater than 4.5 implies A, greater than 3.5 implies B+, greater than 3 implies B and else C.
Write a program to find out the type of the variable Var1 = ——-. suppose 1+2j check whether it is int, float, str, bool, complex, tuple, dict, list, or unknown.
Write a Python program to sum of three given integers. However, if two values are equal sum will be zero.
Write a program to calculate the fare of a journey based on the following conditions, fare will be charged Rs. 15/km for first 100km, for next 200km it will be Rs.14/km, for next 200km it will be Rs.12/km and for distance above 500km, it will be charged Rs.11/km.
Write a routine to convert weight from Kg to pounds or pounds to kg.
8 Loops
Loops are one of the most powerful and basic concepts in programming. A loop can contain a set of statements that keeps on executing until a specific condition is reached.
Programming languages provide us the concept of loops which helps us in executing some task n number of times where n can be any whole number. They are pretty useful and can be applied to various use cases.
There are two types of loops in Python.
8.1 The “for” loop
For loop iterate over a given sequence (range, list, tuple, string etc.) or other iterable objects. Iterating over a sequence is called traversal. Flow chart of for loop is:
8.2 Looping through String
Even strings are iterable objects, they contain a sequence of characters:
for letter in 'string':
print(letter)
s
t
r
i
n
g
8.3 Looping through a List
= ['ABL', 'MCB', 'NBP']
Banks for bank in Banks:
print(bank)
ABL
MCB
NBP
8.4 How to Use Index
= ['ABL', 'MCB', 'NBP']
Banks for i in range(3):
print(i, Banks[i])
0 ABL
1 MCB
2 NBP
8.5 Use of Enumerate for Indexing
# Loop through the list and iterate on both index and element value
=['red', 'yellow', 'green', 'purple', 'blue']
squares
for i, square in enumerate(squares):
print(i, square)
0 red
1 yellow
2 green
3 purple
4 blue
We can change the elements in a list:
# Use for loop to change the elements in list
= ['red', 'yellow', 'green', 'purple', 'blue']
squares
for i in range(0, 5):
print("Before square ", i, 'is', squares[i])
= 'white'
squares[i] print("After square ", i, 'is', squares[i])
Before square 0 is red
After square 0 is white
Before square 1 is yellow
After square 1 is white
Before square 2 is green
After square 2 is white
Before square 3 is purple
After square 3 is white
Before square 4 is blue
After square 4 is white
Quick Quiz: Print the following pattern using for loop.
+++
++
+++++
+++
+++++++++
list = [3,2,5,3,9]
for i in list:
print('+'*i)
+++
++
+++++
+++
+++++++++
8.6 Iterating over tuples
We can use for loops to iterate on a tuple. The for loop will keep on iterating until the elements in the tuples are exhausted.
= ('SBP', 'NIBAF', 'BSC')
Tuple for entities in Tuple:
print(entities)
SBP
NIBAF
BSC
8.7 The range ( ) function
When using for loops in Python, the range() function is pretty useful to specify the number of times the loop is executed. It yields a sequence of numbers within a specified range.
syntax: range (start, stop, steps)
The first argument is the starting value. It is zero by default.
The second argument is the ending value of the range.
The third argument is the number of steps to take after each yield.
8.7.1 Iterating over range object
# for loop
for i in range(2,10,3):
print(i)
2
5
8
8.7.2 an other for loop with else
for char in 'SBP':
print(char)
else:
print('loop ended')
S
B
P
loop ended
8.8 Nested Loop
A nested loop is a loop inside a loop. The “inner loop” will be executed once for each iteration of the “outer loop” i.e., in each iteration of the outer loop, inner loop execute all its iteration. For each iteration of an outer loop, the inner loop re-start and completes its execution before the outer loop can continue to its next iteration.
= ['Rizwan', 'Adil', 'Ahmad']
list1 = ['JD', 'OG-4', 'SBP']
list2 for officer in list1:
for x in list2:
print(f'({officer}, {x})')
(Rizwan, JD)
(Rizwan, OG-4)
(Rizwan, SBP)
(Adil, JD)
(Adil, OG-4)
(Adil, SBP)
(Ahmad, JD)
(Ahmad, OG-4)
(Ahmad, SBP)
Quick Quiz: Create Co-ordinate (0,0) ,(0,1) ,(0,2) , (1,0) ,(1,1) ,(1,2) ,(2,0) ,(2,1) ,(2,2) ,(3,0) ,(3,1) ,(3,2)
for x in range(4):
for y in range(3):
print(f"({x},{y})")
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)
(3,0)
(3,1)
(3,2)
8.9 The “while” loop
The while loop in Python executes a block of code until the specified condition becomes False.
Flow chart of while loop is :
= 0 # Initializing, To Give an initial value to a variable
count while count<10: # Setting a condition
print(count)
+=2 # Incrementing the initial value by 2 count
0
2
4
6
8
In the example, the while statement checks if count is less than 10.
Initially, count is zero so the statement is true and it executes the body of while. Then the count gets incremented by 2. Again we check the condition and this goes on till the condition becomes false.
Here, when our code checks 10<10, the statement returns False and so the code in while block is not executed.
8.9.1 Example
# While Loop Example
= [1982, 1980, 1973, 2000]
dates
= 0
i = dates[0]
year
while(year != 1973):
print(year)
= i + 1
i = dates[i]
year
1982
1980
print("It took ", i ,"repetitions to get out of loop.")
It took 2 repetitions to get out of loop.
8.10 Infinite loop
A loop is called an infinite loop when the loop will never reach its end.
Usually, when a condition is always True in a while loop, the loop will become an infinite loop. So we should be careful when writing conditions and while updating variables used in the loop.
In Python shell, we can stop/terminate the program on an infinite loop by using CTRL + C. In jupyter notebook press i
twice.
Quick Quiz: Write a program to print 1 to 50 using a while loop.
Quick Quiz: Write a program to print the contents of a list=['C', 'C++', 'java', 'fortran','python']
using while loop.
8.11 Loop control statements in Python
= 0
num while num<10:
+=1
num if num==5:
break
print(num)
1
2
3
4
In this loop, we are incrementing the value of num variable and then printing it. When the num value becomes 5 the break statement is executed which terminates the loop and therefore loop is not executed further.
= 0
num while num<10:
+=1
num if num==5:
continue
print(num)
1
2
3
4
6
7
8
9
10
Here, we see that when the num variable is equal to 5, the continue statement is executed. It then doesn’t execute the lines after the continue statement and the control is sent to the next iteration.
8.12 Common Mistakes
Mostly people forgte to initialize the variable.
There is second issue, we might face if we forget to initialize the variables with the right value. we might have already used the variable in our program. if we reuse a variable without setting the correct value from the start, it will still have the value from before.
=1
xsum = 0
while x<10:
sum+=x
+=1
xprint(sum)
45
Whenever you are writing a loop, check that you are initializing all the variables you want to use before you use them.
= 1
product =1
xwhile x<10:
=product*x
product+=1
xprint(product) # what we call this outcome!
362880
8.13 Exercise
A list of groceries is given below, print all items with its index.
groceries = ["bananas","butter","cheese","toothpaste"]
Make a combination of all the letters of ‘SBP’ and ‘NIBAF’
Write a program to say “hello” to all persons in a list which starts with M.
List = ['Ahmad', 'Muhammad', 'Essa', 'Mossa']
Print odd numbers in first 10 numbers using while loop.
Also find the sum of all numbers in above question.
Write a program to print the multiplication table of a number entered by the user, using ‘for’ loop.
Attempt above problem using while loop.
Find the total of
[10,20,30]
using for loop.Write a program to guess a secrete number in 3 attempts using while loop.
Solve above problem while generating secrete number randomly.
Provide a hint to make problem easy, if guess is larger, then print ‘its larger’, otherwise ‘its smaller’
Write a program whether a given number is prime or not.
Find the prime numbers in a given range.
store the numbers obtained in above question as a list.
Find the sum of all the numbers in the list above in question 14.
Challenge: calculate the time required to run the above code 500 times.
Draw the following pattern using nested loop.
# xxxxx # xx # xxxxx # xx # xx
Make the co-ordinates (0,0,0) …(2,2,2) using nested for loop.
Write a
for
loop the prints out all the element between -5 and 5 using the range function.Write a while loop to display the values of the Rating of an album playlist stored in the list
PlayListRatings
. If the score is less than 6, exit the loop. The listPlayListRatings
is given by:PlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]
Write a program to sum first n natural numbers, take input from user.
Write program to find the factorial of a number n.
Write a program to print the following pattern.
* * * * * * * * * * * * * * *
Write a Python program to concatenate all elements in a list into a string and return it
Write a nested
for
loop program to print multiplication table in Python from 2 to 10.Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.
= [386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345, 399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217, 815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717, 958,743, 527] numbers
Write a program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included) and print the result in the form of a list.
9 List Comprehensions
List comprehension is an elegant way to define and create lists based on existing lists. It offers a shorter syntax when you want to create a new list based on the values of an existing list.
9.1 Example
Iterating through a string Using for Loop
= []
n_letters for letter in 'NIBAF':
n_letters.append(letter)
print(n_letters)
['N', 'I', 'B', 'A', 'F']
Iterating through a string Using List Comprehension
=[letter for letter in 'NIBAF']
n_letters
print(n_letters)
['N', 'I', 'B', 'A', 'F']
If you noticed, ‘NIBAF’ is a string, not a list. This is the power of list comprehension. It can identify when it receives a string or a tuple and work on it like a list.
9.2 Example
Based on a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
= ['apple', 'banana', 'kiwi','mango', 'cherry']
fruits = []
fruits_a for fruit in fruits:
if 'a' in fruit:
fruits_a.append(fruit)print(fruits_a)
['apple', 'banana', 'mango']
This can be done in one line of code With list comprehension:
= ['apple', 'banana', 'kiwi','mango', 'cherry']
fruits = [fruit for fruit in fruits if 'a' in fruit]
fruits_a
print(fruits_a)
['apple', 'banana', 'mango']
9.3 The Syntax
new_list = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
9.4 Key Points to Remember
List comprehension is an elegant way to define and create lists based on existing lists.
List comprehension is generally more compact and faster than normal functions and loops for creating list.
However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.
Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.
9.5 Exercise
Create the list
[1,2,3,4,5]
using list comprehension.Use a list comprehension that iterates over a_list, prints a list composed of each value in a_list multiplied by 10.
a_list = list(range(1, 11))
Use a list comprehension that iterates over a_list, prints a list composed of odd numbers from 1 to 9.
Using a list comprehension which iterates over a_list and whose output expression accesses a value from a dictionary, print a list composed of the text form of each even number from 2 to 10, e.g.,
[ 'two', 'four', 'six', 'eight', 'ten' ].
a_dictionary = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five', 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten'}
Prompt the user for a number, which will be returned from input as a string data type. Strings can be iterated over like lists, such that the loop repeats for each character in the string. Using a list comprehension which iterates over the user-entered string and whose output expression accesses values from a_dictionary, print a list of the text form of each digit from the user-entered string, e.g., Enter a number: 195 return
[ 'one', 'nine', 'five' ]
Using the same user-entered number and list comprehension as above, also print the text form of the digits in a single string (using the string join function) with a dash between each text form of the digit, e.g.,
one-nine-five
Write a list comprehension that builds a list containing only the names with at least 4 characters.
list9 = ['SBP', 'NIABF', 'HoK', 'PSPC', 'DPC']
Write a list comprehension that builds a list containing only even numbers over 40.
numbers = list (range (10,50,5))
Add % in front and end of every single word in a given string str: “Fall is Awesome in Sakardu” only using list comprehensions. Desired Output
['%Fall%','%is%','%Awesome%','%in%','%Sakardu%']
Use list comprehension to make a list of the first letter of each word in the following list:
wordList = ["this", "is", "an", "apple"]
A string is given:
msg = "Long Live Pakistan!"
Write a list comprehension that prints a list
['L', 'o', 'n', 'g', 'L', 'i', 'v', 'e', 'P', 'a', 'k', 'i', 's', 't', 'a', 'n']
Do not print out the space or the !.
10 Functions and Recursion
10.1 Function
A function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable any number of time.
10.1.1 Syntax
def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition that consists of the following components.
Keyword
def
that marks the start of the function header.A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
Parameters (
arguments
) through which we pass values to a function. They are optional.A colon (:) to mark the end of the function header.
Optional documentation string (doc string) to describe what the function does.
One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
The statement
return
exits a function, optionally passing back a value..
10.1.2 Example
def greet(name):
'''Greeting Function'''
print("Welcome to the World of Python, " +name)
"Raja") greet(
Welcome to the World of Python, Raja
10.1.3 Quick Quiz
Define a function to return the absolute value of the entered number.
Define a function to day Hello, good morning “name”, if the person in your contact list, otherwise ask “Who are You”
10.2 Type of functions
Basically, we can divide functions into the following two types:
Built-in functions
- Functions that are built into Python.User-defined functions
- Functions defined by the users themselves.
For example, len( ), range ( ) and print( ) are built-in functions
, and the greet function
defined above is a user-defined function
.
10.3 Functions with arguments
def greet1(name,msg):
print("Hello", name +', '+msg)
'ahmad', 'how are you') greet1(
Hello ahmad, how are you
Here, the function greet1()
has two parameters.
Since we have called this function with two arguments, it runs smoothly and we do not get any error.
If we call it with a different number of arguments, the interpreter will show an error message. Below is a call to this function with one and no arguments along with their respective error messages.
def greet1(name,msg):
print("Hello", name +', '+msg)
'ahmad') greet1(
Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: greet1() missing 1 required positional argument: 'msg'
Detailed traceback:
File "<string>", line 1, in <module>
10.4 Default argument or parameter value
Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.
def greet1(name ,msg="How do you do"):
print("Hello", name +', '+msg)
'Ahmad') greet1(
Hello Ahmad, How do you do
The input to a function is called a formal parameter.
A variable that is declared inside a function is called a local variable. The parameter only exists within the function (i.e. the point where the function starts and stops).
A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout the program.
def square(a): # formal parameter
'''
This function will return the sqaure of number plus 1
'''
= 1 # local variable
b = a*a + b
c return c
print(square(2))
5
10.5 Recursive function
Recursion is the process of defining something in terms of itself. That is, a function that calls itself. For example:
factorial(n)=n * factorial(n-1)
10.5.1 Example:
#n! = 1*2*3*...*n
=3
n= 1
product for i in range(n):
= product*(i+1)
product print(product)
6
10.5.2 Return Values
The Python return statement is a special statement that you can use inside a function or method to send the function’s result back to the caller. To let a function return a value, use the return statement:
above example can be wrapped in a function as:
def fact(n):
= 1
product for i in range(n):
=product*(i+1)
productreturn product
print(fact(3))
6
Using Recursion
def recur_factorial(n):
"""This is a recursive function
to find the factorial of an integer"""
if n==1:
return 1
else:
return (n*recur_factorial(n-1))
print(recur_factorial(3))
6
10.6 Pre-defined Functions
There are many pre-defined functions in Python, so let’s start with the simple ones.
The print()
function:
# Build-in function print()
= [10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5]
list1 print(list1)
[10.0, 8.5, 9.5, 7.0, 7.0, 9.5, 9.0, 9.5]
The sum()
function adds all the elements in a list or tuple: try pease
The len()
function show the length a list or tuple: try please
10.7 Exceptions
An exception is an error that occurs during the execution of code. This error causes the code to raise an exception and if not prepared to handle it will halt the execution of the code.
10.7.1 Exampls
Run each piece of code and observe the exception raised
1/0
Error in py_call_impl(callable, dots$args, dots$keywords): ZeroDivisionError: division by zero
Detailed traceback:
File "<string>", line 1, in <module>
= a+5 y
Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: unsupported operand type(s) for +: 'set' and 'int'
Detailed traceback:
File "<string>", line 1, in <module>
= [1,2,3]
a 5] a[
Error in py_call_impl(callable, dots$args, dots$keywords): IndexError: list index out of range
Detailed traceback:
File "<string>", line 1, in <module>
10.8 Exercise_Functions
Create a function
con
that add two number .Can the
con
function we defined before be used to concatenate lists or tuples?Write a function named odd_or_zero which takes one parameter, a number, and returns that number if it is odd or returns 0 if the number is even. Then using a list comprehension which iterates over a_list and calls your odd or zero function for each value, print a list like the following:
[ 1, 0, 3, 0, 5, 0, 7, 0, 9, 0 ]
Define a function to find the greatest of three numbers using.
How do you prevent python print( ) function to print a new line at the end.
Write a recursive function to calculate the sum of first n natural numbers.
Write a function to print first n lines of the following pattern.
*****
***
*Write a function which converts inches in cm
Write a function to remove a given word from a string and strip it at the same time.
Write a Python function that takes a list and returns a new list with unique elements of the first list. Sample List :
[1,2,3,3,3,3,4,5]
, Unique List :[1, 2, 3, 4, 5]
2.3 Comments
A Python comment is line of text in a program that is not executed by the interpreter. Comments can be used during debugging to identify issues and to explain code.
Single Line Comments –> You can write using #
Multiple lines Comments –> you can write using ```
comment
```2.3.1 Print Function
The
print()
function prints the specified message to the screen. The message can be a string, or any other object. The full syntax ofprint()
is:2.3.2 Parameters of Print Function
objects - object to be printed. * indicates that there may be more than one object
sep - objects are separated by sep. Default value:
' '
end - end is printed at last. Default is ‘\n’ (line feed)
file - must be an object with write(string) method. If omitted,
sys.stdout
will be used which prints objects on the screen.flush - If True, the stream is forcibly flushed. Default value:
False
2.3.3 First Python Program
Let’s write our first python program . Create a file name name.py and write the following code. Execute this (.py file) and you will see the output of your program.