0% found this document useful (0 votes)
27 views

Python Programming Lectures.

This document provides an overview of Python programming concepts including: - Installing Python and Jupyter Notebook - Variables, operators, data types - Strings, functions, conditionals and loops - Defining functions, passing arguments, return values - Recursion It then provides examples and exercises to practice key concepts like loops, conditionals, functions.

Uploaded by

Sheraz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Python Programming Lectures.

This document provides an overview of Python programming concepts including: - Installing Python and Jupyter Notebook - Variables, operators, data types - Strings, functions, conditionals and loops - Defining functions, passing arguments, return values - Recursion It then provides examples and exercises to practice key concepts like loops, conditionals, functions.

Uploaded by

Sheraz
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

PYTHON PROGRAMMING

LECTURES.
Python:

Installation

https://www.python.org/downloads/windows/
Python:

www.anaconda.com
Python:

Type anaconda prompt

(base)c:\user\abc> jupyter notebook


Python:
Jupyter Notebook
Variable and Operators:

Variables are kind of placeholders or these are names or symbols that can hold different kind
of values in it. Python supports several kind of variable like integer, float, string….etc.

x=2

y=5

c= 7.2

a,b= 4, 5.0
When we assigned the value x we never specified that it is integer that’s what we call it as
dynamically typed. Based on the content the type is defined automatically.
Type()
Arithmetic Operator

Symbols Task Perfomed


+ Addition
- Substraction
/ Division
% MOD
* Multiplication
// Floor Division
** To the power of
Type bool & Comparison

Symbols Task Perfomed


== True, if it is equal
!= True, if not equal to
> Greater than
< Less than
>= Greater than equal to
<= Less than equal to
Practice Question:

Write a python program to check a triangle is equilateral,


isosceles or scalene.
Take input lengths of the triangle sides and then print it is
equilateral , isosceles or scalene.
x=int(input("enter length of side 1 of triangle"))
y=int(input("enter length of side 2 of triangle"))
z=int(input("enter length of side 3 of triangle"))
if x==y and y==z and x==z:
print("it is equilateral triangle")
elif (x==y or x==z or y==z):
print("It is isoseles traingle")
else:
print("it is scalen triangle")
String Functions:

Len()

Upper()

Lower()

Endswith()

Count()

Capitalize

Find()

Replace(oldword ,newword)
Scape Sequence;

\n

\\

\’

\t
…….E.t.c
Iteration:

For Loop

While Loop

Repeat Until Loop


Python For Loop:

A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.
• Looping Through a List, Tuple, Dictionary , Set, String

• Looping Through the range() Function


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.
for x in range(6):
print(x)
Python For Loop:

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() function defaults to 0 as a starting value, however it is
possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1,
however it is possible to specify the increment value by adding a
third parameter: range(2, 30, 3):
for x in range(2, 30, 3):
print(x)
Python For Loop:

The break Statement:


With the break statement we can stop the loop before it has looped through all the items:

for x in range(6):
if x==4:
break
print(x)

Exit the loop when x is 4:


Python For Loop:

The continue Statement:


With the continue statement we can stop the current iteration of the loop, and continue with
the next:

for x in range(6):
if x==4:
continue
print(x)
Python For Loop:

Else in For Loop:


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

for x in range(6):
print(x)
else:
print("Finally finished!")
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break
statement.
Practice Question:

Write a program to print odd number between 1 to 100

Write a program to print the table of number input by user up to 10.

Write a program to print numbers from 1 to 20 , except 7.

Write a program to find the number input by user is prime or not?


Python While Loop:
With the while loop we can execute a set of statements as long as a condition is true.

i=1
while i < 6:
print(i)
i += 1
Print i as long as i is less than 6:
Note: remember to increment i, or else the loop will continue forever.
The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.
Python While Loop:
The break Statement:

With the break statement we can stop the loop even if the while condition is true:
Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Python While Loop:
The continue Statement:

With the continue statement we can stop the current iteration, and continue with the next:
Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Python While Loop:
The else Statement:

With the else statement we can run a block of code once when the condition no longer is
true:
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")
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.
In Python a function is defined using the def keyword:
Example
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)

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Arguments are often shortened to args in Python documentations.
Parameters or Arguments?
The terms parameter and argument can be used for the
same thing: information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses
in the function definition.
An argument is the value that is sent to the function
when it is called.
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("Emil", “Franses")

If you try to call the function with 1 or 3 arguments, you


will get an error:Example

This function expects 2 arguments, but gets only 1:


def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil")
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")
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))
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:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Arbitrary Arguments are often shortened to *args in Python documentations.


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 = "Emil", child2 = "Tobias", child3 = "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:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations.


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
Recursion

Python also accepts function recursion, which means a defined


function can call itself.
Recursion is a common mathematical and programming
concept. It means that a function calls itself. This has the benefit
of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be
quite easy to slip into writing a function which never terminates, or
one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient
and mathematically-elegant approach to programming.
In this example, tri_recursion is a function that we have defined to
call itself ("recurse"). We use the k variable as the data, which
decrements (-1) every time we recurse. The recursion ends when
the condition is not greater than 0 (i.e. when it is 0).
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)

You might also like