CT

Download as pdf or txt
Download as pdf or txt
You are on page 1of 110

What is Python?

Python is a popular programming language. It was created by Guido van Rossum


in the late 1980s.

Python is a general-purpose, dynamically typed, high-level, compiled and


interpreted, garbage-collected, and purely object-oriented programming language
that supports procedural, object-oriented, and functional programming.

Python is the programming language of choice for professionals working in fields


such as Artificial Intelligence, Machine Learning (ML), Data Science, the Internet
of Things (IoT), etc., because it excels at both scripting applications and as
standalone programmes.

1
Python Indentation
• Python programming provides no braces to indicate blocks of code for class
and function de nitions or ow control.
• Blocks of code are denoted by line indentation
• Indentation refers to the spaces at the beginning of a code line.
• In other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
• Python uses indentation to indicate a block of code.

if 5 > 2: if 5 > 2:
print("Five is greater than two!") print("Five is greater than two!")

2
fi
fl
Python Comments

- Python has commenting capability for the purpose of in-code documentation.


- Comments start with a #, and Python will render the rest of the line as a
comment.
- Comments can be used to explain Python code.
- Make the code more readable.
- Can be used to prevent execution when testing code.

#This is a comment.
print("Hello, World!")

3
Python Variables

- Variables are containers for storing data values.


- In Python, variables are created when you assign a value to it.

x=5
x=5 y = "John"
y = "Hello, World!" print(x)
print(y)

4
Variable Names- Naming Convention
A variable can have a short name (like x or y) or a more descriptive name (age,
carname, total_volume).

Rules for Python variables:


• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
• A variable name cannot be any of the Python keywords.

5
VALID INVALID
myvar = "John"
my_var = "John" 2myvar = "John"
_my_var John my-var = "John"
myVar = "John" my var = "John"
MYVAR = "John"
myvar2 = "John"

Remember that variable names are case-sensitive

6
Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

7
One Value to Multiple Variable

You can assign the same value to multiple variables in one line:

x = y = z = "Orange"
print(x)
print(y)
print(z)

8
Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to
extract the values into variables. This is called unpacking.

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

9
Output Variables

The Python print() function is often used to output variables.

x = "Python is awesome"
print(x) Output: Python is awesome

In the print() function, you output multiple variables, separated by a


comma:

x = "Python"
y = "is"
z = "awesome" Output: Python is awesome
print(x, y, z)

10
You can also use the + operator to output multiple variables:

x = “Python "
y = “is "
z = "awesome"
print(x+y+z)

Notice the space character after "Python " and "is ", without
them the result would be "Pythonisawesome".

11
For numbers, the + character works as a mathematical operator:

VALID INVALID

X =5 X=5
Y = 10 Y = “John”
print(X+Y) print(X + Y)

12
The best way to output multiple variables in the print() function is to
separate them with commas, which support different data types:

X=5
Y = “John”
print(X, Y)

13
Case-Sensitivity of Python Variables

Python variables are case sensitive which means Age and age are
two different variables:

age = 20
Age = 30

print( "age =", age )


print( "Age =", Age ) Output:

age = 20
Age = 30

14
Python Local Variables

Python Local Variables are defined inside a function. We can not


access variable outside the function.

def sum(x, y):


sum = x + y
return sum
print(sum(5, 10))
Output:
15

15
Python Data Types

• Python data types are actually classes, and the de ned variables are their
instances or objects.
• Since Python is dynamically typed, the data type of a variable is determined at
runtime based on the assigned value.
• Variables can store data of different types, and different types can do different
things.

Text Type: str

Numeric Types: int, float, complex

Sequence list, tuple, range


Types:

16
fi
Python Numeric Data Types

var1 = 1 — Int
var2 = True — Boolean
var3 = 10.023 — Float
var4 = 10+3j — Complex

17
Python String Data Type

• Python string is a sequence of one or more Unicode characters, enclosed in


single, double or triple quotation marks (also called inverted commas).
• Python strings are immutable which means when you perform an operation on
strings.
• You always produce a new string object of the same type, rather than
mutating an existing string.

18
str = “Hello World!”

1 print(str) — Prints complete string


2 print(str[0]) — prints first character of the string
3 print(str[2:5]) — Prints character starts from 3rd to 5th
4 print(str[2:]) — prints string starting from 3rd to end
5 print(str * 2) — prints string two times
6 print(str + "TEST") — prints concatenated strings

Output

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
19
Type Casting
If you want to specify the data type of a variable, this can be done with casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = oat(3) # z will be 3.0

You can get the data type of a variable with the type() function.

x=5 Output:
y = "John"
print(type(x)) Int
print(type(y)) Str

20
fl
Python Operators

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

21
Arithmetic Operators

22
Assignment Operators

23
Comparison Operators

24
Logical Operators

25
Bitwise Operators

26
Operator
Precedence

27
a = int(input("Enter value for a"))
b = int(input("Enter value for b"))

print("The number you have entered for a is ", a)


print("The number you have entered for b is ", b)

• The input() function is used to take input from the


user through keyboard.
• In Python, the return type of input() is string only, so we have
to convert it explicitly to the type of data which we require. In our
example, we have converted to int type explicitly
through int( ) function.
• print() is used to display the output.

Enter value for a 10


Enter value for b 20

The number you have entered for a is 10


The number you have entered for b is 20

28
Strings
Strings in python are surrounded by either single quotation marks,
or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function

Example
print("Hello")
Output
print('Hello')
Hello
Hello

29
Quotes Inside Quotes

We can use quotes inside a string, as long as they don't match the quotes
surrounding the string
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

Output
It's alright
He is called 'Johnny'
He is called “Johnny"

30
Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an


equal sign and the string

Example
a = "Hello"
print(a)

Output

Hello

31
Multiline Strings
We can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes
a = """Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string"""
print(a) Output

Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string

32
Or three single quotes
a = ‘’’Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string’’’
print(a)
Output

Assigning a string to
a variable is done with
the variable name followed by an
equal sign and the string

33
Strings are Arrays

Like many other popular programming languages, strings in Python are arrays of
bytes representing unicode characters.

However, Python does not have a character data type, a single character is
simply a string with a length of 1.

Square brackets can be used to access elements of the string.

Example

Get the character at position 1 (remember that the rst character has the position 0):
Output
a = "Hello, World!"
print(a[1])
e 34
fi
Looping Through a String

Since strings are arrays, we can loop through the characters in a string,
with a for loop.

Example
Loop through the letters in the word "BANANA"

for x in "BANANA":
print(x) Output

B
A
N
A
N
A

35
String Length

To get the length of a string, use the len() function

Example

a = "Hello, World!"
print(len(a))

Output

13

36
Check String

To check if a certain phrase or character is present in a string,


we can use the keyword in.

Example
Check if "free" is present in the following text: Output

txt = "The best things in life are free!" True


print("free" in txt)

Use it in an if statement

txt = "The best things in life are free!" Output


if "free" in txt:
print("Yes, 'free' is present.") Yes, 'free' is present.

37
Check if NOT

To check if a certain phrase or character is NOT present in a string,


we can use the keyword not in.

Example
Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!" Output


print("expensive" not in txt)
True
Use it in an if statement:
txt = "The best things in life are free!"
if “expensive" is not in txt: Output
print("No, 'expensive' is NOT present.”)
No, 'expensive' is NOT present.
38
PRACTICE PROBLEMS

1.Write a program to create a new string made of an input string’s rst,


middle, and last character.

2. Write a program to create a new string made of the middle three


characters of an input string.

3. Given two strings, s1 and s2. Write a program to create a new string s3
by appending s2 in the middle of s1.

39

fi
Python - 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, to return a part of
the string.
Example
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5]) Output

llo
The first character has index 0.

40
Slice From the Start

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])
Output

Hello

41
Slice To the End
By leaving out the end index, the range will go to the end:

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])

Output

llo, World!

42
Negative Indexing

Use negative indexes to start the slice from the end of the string:

Example

Get the characters:

From: "o" in "World!" (position -5)


To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])

43
Python - Modify Strings
Python has a set of built-in methods that you can use on strings.
1. Upper Case

The upper() method returns the string in upper case


Output
a = "Hello, World!"
print(a.upper())
HELLO, WORLD!
2. Lower Case
The lower() method returns the string in lower case:

a = "Hello, World!" Output


print(a.lower())
hello, world!

44
Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often
you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


Output
print(a.strip())
Hello, World!

45
Replace String

The replace() method replaces a string with another string:

Example
a = " Hello, World! " Output
print(a.replace(“H”, “J”))
Jello, World!

46
Split String
The split() method returns a list where the text between the speci ed separator
becomes the list items.

Example
The split() method splits the string into substrings if it finds instances of the
separator:

a = " Hello, World! "


b = a.split(“,”) Output
print(b)
['Hello', ' World!']

47

fi
String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Example
Merge variable a with variable b into variable c:
a = “Hello" Output
b = “World!”
c = a + b HelloWorld!
print(c)
To add a space between them, add a " ":

a = “Hello" Output
b = “World!”
c = a + “ ” +b Hello World!
print(c)
48
String Format
F-Strings
To specify a string as an f-string, simply put an f in front of the string literal,
and add curly brackets { } as placeholders for variables and other operations.
Example
Create an f-string:

Age = 36
txt = f"My name is John, I am {Age}”
print(txt)
Output

My name is John, I am 36

49
Placeholders and Modi ers
A placeholder can contain variables, operations, functions, and modi ers to
format the value.

Example
Add a placeholder for the price variable:
price = 59
txt = f"The price is {price} dollars"
print(txt)

50
fi
fi
A placeholder can include a modi er to format the value.
A modi er is included by adding a colon : followed by a legal formatting type, like
.2f which means xed point number with 2 decimals:

Example
Display the price with 2 decimals:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Output

The price is 59.00 dollars

51
fi
fi
fi
A placeholder can contain Python code, like math operations:

txt = f"The price is {20 * 59} dollars"


print(txt)

Output

The price is 1180 dollars

52
Escape Character

- To insert characters that are illegal in a string, use an escape character.

- An escape character is a backslash \ followed by the character you


want to insert.

- An example of an illegal character is a double quote inside a string that


is surrounded by double quotes:

An example of an illegal character is a double quote inside a string that is


surrounded by double quotes:

txt = "To insert characters that are “illegal” in a string"

You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
53
To x this problem, use the escape character \"

Example
The escape character allows you to use double quotes when you
normally would not be allowed:

txt = "To insert characters that are \“illegal\” in a string"

54
fi
55
PRACTICE PROBLEMS

1. Introduce Yourself

You have a few Python variables that describe your age, name, and
favorite food:

name = "Rohan"
age = 27
favourite_food = "Pizza"

Using these variables, create the following string to introduce yourself:

"Hi! My name is Rohan. I am 27 years old, and my


favorite food is Pizza."

56
Solution

name = "Rohan"
age = 27
favourite_food = "Pizza"

intro_string = f"Hi! My name is {name}. I am {age} years


old, and my favorite food is {favourite_food}."

print(intro_string)

# output:

Hi! My name is Rohan. I am 27 years old, and my favorite


food is Pizza.

57
2. Letters in a Name

You are asked to create a chatbot at work.

Create a code that asks the user for their full name. Then it should count the
number of letters in their name, ignoring spaces. Finally, it should greet the
user and inform them of the length of their name.

58
Solution

full_name = input("Please enter your full name: “)

letter_count = len(full_name.replace(" ", “"))

print(f"Hello, {full_name}! Your name has


{letter_count} letters, excluding spaces.")

59
PRACTICE PROBLEMS

1.Write a program to create a new string made of an input string’s rst, middle,
and last character.

2.Write a program to create a new string made of the middle three characters of
an input string.

3.Given two strings, s1 and s2. Write a program to create a new string s3 by
concatenating s1 and s2

60
fi
Python If Statement

• The if statement in Python evaluates whether a condition is true or false.


• It contains a logical expression that compares data, and a decision is made
based on the result of the comparison.

Syntax
if expression:
# statement(s) to be executed

61
62
63
Python if else Statement

The if-else statement in Python is used to execute a block of code when


the condition in the if statement is true, and another block of code when
the condition is false.

Syntax

if expression:
# code block to be executed
#
else:
# code block to be executed
#

64
65
66
Python if…elif…else Statement
• The if elif else statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
• Similar to the else block, the elif block is also optional.
• However, a program can contains only one else block whereas there can be an
arbitrary number of elif blocks following an if block.

Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s) 67
68
PRACTICE PROBLEMS

1. Write a program to check whether the given input number is divisible by 3 or else
show a message “Number is not divisible by 3”.

2. Write a program that checks whether the given input is an even number or an odd
number.

3. Write an if/else statement with the following condition: If the variable age is
greater than 18, output "Old enough", otherwise output "Too young”.

4. Write a program that takes input a number from user & state whether the number
is positive, negative or zero.

5. Write a program that takes a character (i.e. string of length 1) and returns true if it
is a vowel, false otherwise.

69
Python for Loop

In Python, we use a for loop to iterate over sequences


such as lists, string, dictionaries, etc.

Syntax
for val in sequence:
# body of the loop

70
Example:

Output:
apple
banana
cherry

71
Example: Loop Through a String

for x in “BANANA":
print(x)

Output:
B
A
N
A
N
A

Printed each character of the string using a for loop.

72
The break Statement

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

Example:

Exit the loop when x is "banana":

Output:
apple
banana

73
Exit the loop when x is "banana", but this time the break comes
before the print:

Output:
apple

74
The continue Statement

With the continue statement we can stop the current iteration of the loop,
and continue with the next:
Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits: Output:
if x == "banana": apple
continue
print(x) cherry

75
for Loop with Python range()

To loop through a set of code a speci ed 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 speci ed number.
Example
Output:
for x in range(6): 0
print(x) 1
2
3
4
5
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

76
fi
fi
The range() function defaults to 0 as a starting value, however it is
possible to specify the starting value by adding a parameter: range(2,
6), which means values from 2 to 6 (but not including 6):

Example
Output:
for x in range(2, 6): 2
print(x) 3
4
5

77
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):
Output:
2
Example
5
8
Increment the sequence with 3 (default is 1):
11
14
for x in range(2, 25, 3): 17
print(x) 20
23

78
Else in For Loop

The else keyword in a for loop specifies a block of code to be


executed when the loop is finished:

Example
Print all numbers from 0 to 5, and print a message
when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

79
The else block will NOT be executed if the loop is stopped by a break statement.

Example
Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

80
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":

Example
Output:
Print each adjective for every fruit:

81
The pass Statement

for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.

Example:
for x in [0, 1, 2]:
pass

82
PRACTICE PROBLEMS

1.Print the rst 10 natural numbers using for loop.


2.Python program to print all the even numbers within the given range.
3.Python program to calculate the sum of all numbers from 1 to a given number.
4.Python program to calculate the sum of all the odd numbers within the
given range.
5.Python program to print a multiplication table of a given number

83
fi
PRACTICE PROBLEMS
1.Write a python program to Iterate through the list, ['Python', 'Numpy','Pandas','Django',
'Flask'] using a for loop and print out the items.
2.Write a python program to iterate from 0 to 100 and print only even numbers
3.Write a python program to iterate from 0 to 100 and print only odd numbers
4.Print the following pattern
#
##
###
####
#####

5. Print the following pattern


1
12
123
1234
12345

6. Write a program for printing Multiplication Table of 10 Using Python nested loops.
84
Syntax
while condition:
statements
The while Loop
With the while loop we can execute a set of statements as long as a
condition is true.
Example
Output
Print i as long as i is less than 10: 1
2
i=1 3
while i < 10: 4
5
print(i)
i += 1
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 de ne an indexing variable, i, which we set to 1.
85
fi
The break Statement

With the break statement we can stop the loop even if the while
condition is true:

Example
Exit the loop when i is 3:

i=1 Output
while i < 10: 1
2
print(i) 3
if i == 3:
break
i += 1

86
The continue Statement

With the continue statement we can stop the current iteration,


and continue with the next:

Example
Continue to the next iteration if i is 3:

i=0
Output
while i < 6: 1
i += 1 2
if i == 3: 4
5
continue 6
print(i)
87
The else Statement

With the else statement we can run a block of code once when the
condition no longer is true:

Example
Print a message once the condition is false:

i=1 Output
while i < 6: 1
2
print(i) 3
i += 1 4
else: 5
print("i is no longer less than 6") I is no longer less than 6

88
Python Functions

• Python Functions is a block of statements that return the speci c task.

• The idea is to put some commonly or repeatedly done tasks together and
make a function.

• instead of writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and over again.

fi
89
Types of Functions in Python

Below are the different types of functions in Python:

1. Built-in library function: These are Standard functions in Python that are
available to use.

2. User-de ned function: We can create our own functions based on our
requirements.

90
fi
Creating a Function in Python

• Using the def keyword, we can de ne a function in Python.


• We can add any type of functionalities and properties to it as we
require.
Example:

def fun():
print(“Hello world”)

91
fi
Calling a Function in Python

• After creating a function in Python we can call it by using the name of the
functions followed by parenthesis containing parameters of that particular
function.

Example:
Output:
# A simple Python function
Hello world
def fun():
print(“Hello world”))

# Driver code to call a function


fun()

92
Python Function with Parameters
• Similar to the return type of functions and data type of arguments in C/C++, this is also
possible in Python (speci cally in Python 3.5 and later).
• Information can be passed into functions as arguments.
• Arguments are speci ed after the function name, inside the parentheses. You can add
as many arguments as you want, just separate them with a comma.

Python Function Syntax with Parameters


Syntax:

def function_name(parameter: data_type)


# body of the function
return expression

93
fi
fi
The following example has a function with one argument (fname). When the
function is called, we pass along a rst name, which is used inside the function to
print the full name:

Example:
Output:
def my_function(fname):
print(fname + " John”)
Emil John
my_function("Emil") Tobias John
my_function("Tobias") Linus John
my_function("Linus")

Arguments are often shortened to args in Python documentations.


94
fi
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 de nition.
- An argument is the value that is sent to the function when it is called.

95

fi
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: Output:
def my_function(fname, lname):
print(fname + " " + lname)
Emil John
my_function("Emil", “John")

This function expects 2 arguments, and gets 2 arguments

96
Example:

def add(num1: int, num2: int):


#Add two numbers
num3 = num1 + num2
return num3
Output:

# Driver code The sum of 5 and 15 results 20.


num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The sum of {num1} and {num2} results {ans}.")

97
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 de nition.
- 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]) Output:

my_function("Emil", "Tobias", "Linus") The youngest child is Linus

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


fi
98
Keyword Arguments (named arguments)

- We 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")

Output:
The youngest child is Linus

The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
99
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 de nition.
- 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 = "Tobias", lname = “John")


Output:
His last name is John 100

fi
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)
Output:
my_function("Sweden")
my_function("India") I am from Sweden
my_function() I am from India
my_function("Brazil") I am from Norway
I am from Brazil

101
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.

Eg: if you send a List as an argument, it will still be a List when it reaches the
function
Example
Output:
def my_function(food):
for x in food:
print(x) Apple
Banana
fruits = ["Apple", "Banana", "Cherry"]
Cherry
my_function(fruits)

102
Return Values

To let a function return a value, use the return statement:

Example:

def my_function(x): Output:


return 5 * x

print(my_function(3)) 15
print(my_function(5)) 25
print(my_function(9)) 45

103
The pass Statement

- Function de nitions cannot be empty.


- For some reason have a function de nition with no content, put in
the pass statement to avoid getting an error.

Example

def myfunction():
pass

104
fi
fi
Positional Arguments

• Values are passed to the function based on their position or order.


• The rst argument is assigned to the rst parameter, the second argument to
the second parameter.
• The order in which you pass the arguments matters.

Example: Output:

def greet(name, message):


Hello Alice
print(f"{message}, {name}!”)
greet("Alice", "Hello")

105
fi
fi
Keyword Arguments

• Values are passed to the function by explicitly specifying the parameter


names.
• The order in which you pass the arguments does not matter because each
argument is matched with a parameter by name.

Example:
Output:

def greet(name, message):


Hello Alice
print(f"{message}, {name}!”)
greet(name = “Alice”, message = “Hello”)

106
Positional-Only Arguments

- You can specify that a function can have ONLY positional arguments, or ONLY
keyword arguments.
- To specify that a function can have only positional arguments, add , / after the
arguments.

Example
Output:
def my_function(x, /):
print(x) 3

my_function(3)
def my_function(x):
Output:
print(x)

my_function(x = 3) Error
107
Keyword-Only Arguments

- To specify that a function can have only positional arguments, add *, after the
arguments.
def my_function(*,x):
Example print(x)

my_function(3)
def my_function(*, x):
print(x)
Output:
my_function(x = 3) Error
Output:
3
108
Combine Positional-Only and Keyword-Only

You can combine the two argument types in the same function.

Any argument before the / , are positional-only, and any argument after the *,
are keyword-only.

Example
Output:
def my_function(a, b, /, *, c, d): 26
print(a + b + c + d)
my_function(5, 6, c = 7, d = 8)

109
Recursion
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the bene t of meaning that you can loop through data to reach a result.

Example

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n * factorial of (n-1)
else:
return n * factorial(n - 1)

# Example usage
n= factorial(5)
print(f"The factorial is {n}")
110
fi

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy