0% found this document useful (0 votes)
10 views77 pages

Introduction to Python Programming

This document provides an overview of Python programming, covering its history, features, and fundamental concepts such as variables, expressions, statements, and debugging. It explains the types of errors that can occur in programming, the structure of a program, and the rules for naming variables. Additionally, it introduces Python's syntax and the use of operators and type converter functions.

Uploaded by

ARUN KUMAR P
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views77 pages

Introduction to Python Programming

This document provides an overview of Python programming, covering its history, features, and fundamental concepts such as variables, expressions, statements, and debugging. It explains the types of errors that can occur in programming, the structure of a program, and the rules for naming variables. Additionally, it introduces Python's syntax and the use of operators and type converter functions.

Uploaded by

ARUN KUMAR P
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

Subject Code : 1BPLC105B CIE Marks : 50

Lecture Hours : 40 (T) 24 (P) SEE Marks : 50

Credits : 04

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Module -1
The way of the program: The Python programming language, what is a program?
What is debugging? Syntax errors, Runtime errors, Semantic errors, Experimental
debugging.
Variables, Expressions and Statements: Values and data types, Variables, Variable names
and keywords, Statements, Evaluating expressions, Operators and operands, Type
converter functions, Order of operations, Operations on strings, Input, Composition,
The modulus operator.
Iteration: Assignment, Updating variables, the for loop, the while statement, The Collatz 3n + 1
sequence, tables, two-dimensional tables, break statement, continue statement, paired
data, Nested Loops for Nested Data.
Functions: Functions with arguments and return values.
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
The Python programming language
- High-level language
- Multi-purpose (Web, GUI, Scripting, etc.)
- Object Oriented
- Interpreted
- Strongly typed and Dynamically typed
- Focus on readability and productivity

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
History of Python:
- Developed by Guido van Rossum during 1980 and 1990 at the National
Research Institute for Mathematics & Computer Science in Netherland
- Derived from ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix
shell and other scripting languages
- Python 1.0 was released in 1994.
- Python 2.0 was released in 2000, 2.7.11 is the latest edition of Python 2
- Python 3.0 was released in 2008
- Python 3.5.1 is the latest version of Python 3

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
Features of Python:
Easy-to-learn: Few keywords, simple structure, clearly defined syntax
A broad standard library: Python's bulk of the library
Interactive Mode: Support interactive testing and debugging of code
Database: Provides interfaces to all major commercial databases
GUI Programming: Supports creation of GUI applications
Scalable: Provides a better structure and support for large programs than
shell scripting
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
The Python programming language
- Python Interpreter :Engine that translates and runs Python code

- Python Interpreter works in two modes: immediate mode and script mode
- Immediate mode (shell): Type Python expressions into Python Interpreter
or shellwindow, and the interpreter
immediately shows the result
- The >>> is called Python prompt
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
The Python programming language
Script mode: Alternatively, you can write a program in a file and use the
interpreter to execute the contents of the file.
- Such a file is called a script, can save to disk, printed, and so on.
- To write a script you need something like a text editor
- Tools which come with both text editor and interpreter, called
Integrated Development Environment or IDE
- For Python: Spyder, Thonny or IDLE, Jupyter NoteBook

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
What is a program ?
- Program is a sequence of instructions that specifies to particular task
- Possible Instructions are
Input: Get data from keyboard or file or some other device such as sensor
Output: Display result on screen or send to file or other device such as motor
Math: Perform basic mathematical operations
Conditional execution: Check for certain conditions and execute the
appropriate sequence of statements.
Repetition: Perform some action repeatedly, usually with some variation
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
What is a debugging ?
- While writing programs, programmer can do mistake
- It often leads to errors
- Programming errors are called bugs
- The process of tracking down and correcting them is called debugging
- Three kinds of errors: syntax errors, runtime errors & semantic errors
- It is a intellectual, challenging and interesting part of programming
- Debugging is like detective work, experimental science

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
Syntax Errors
- Python can execute a program only if program is syntactically correct
- Otherwise, the execution fails and returns an error message
- Syntax refers to the structure of a program and the rules about that
structure

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
Runtime Errors
- The errors can appear only during the execution or run a program
- These errors also called exceptions

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
The way of the Program
Sematic Errors
- If there is a semantic error in the program, program will run successfully
- Computer will not generate any error messages
- The meaning of the program (its semantics) or result will be wrong

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- A value is the fundamental things like: a letter or a number, that
program manipulates
Example: 4 or "Hello, World!“
- Values are classified into classes or data types
- 4 is an integer and "Hello, World!" is a string
- Strings belong to the class str and integers belong to the class int

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- type function can be used to check class of particular value
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
- Numbers with a decimal point belong to a class called float, because
these numbers are represented in a format called floating-point
>>> type(3.2)
<class ‘float'>
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- What about values like "17" and "3.2"? They look like numbers, but they
are in quotation marks like strings
>>> type("17")
<class 'str'>
>>> type("3.2")
<class 'str'>
- Strings in Python can be enclosed in either single quotes ( ' ) or
double quotes ( " ), or three of each ( ''' or """ )

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- Strings in Python can be enclosed in either single quotes ( ' ) or
double quotes ( " ), or three of each ( ''' or """ )
>>> type('This is a string.')
<class 'str'>
>>> type("And so is this.")
<class 'str'>
>>> type("""and this.""")
<class 'str'>
>>> type('''and even this...''')
<class 'str'>

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- Double quoted strings can contain single quotes inside them, as in
"Bruce's beard"
- And single quoted strings can have double quotes inside them, as in
'The knights who say "Ni!" '.

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- Strings enclosed with three occurrences of either quote symbol are
called triple quoted strings
- They can contain either single or double quotes

>>> print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')


"Oh no", she exclaimed, "Ben's bike is broken!"
>>>

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Values and data types
- Triple quoted strings can even span multiple lines:
>>> message = """This message will
... span several
... lines."""
>>> print(message)
This message will
span several
lines.
>>>

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Variables
- A variable is a name that refers to a value
- The assignment statement gives a value to a variable
>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159

- The assignment token = should not be confused with equals token ==


- The assignment token = assign or bind a value at RHS to variable at the LHS

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Variables
>>> message = "What's up, Doc?"
>>> n = 17
>>> pi = 3.14159

- If you ask the interpreter to evaluate a variable, it will produce the value that is
currently linked to the variable:
>>> message
'What's up, Doc?'
>>> n
17
>>> pi
3.14159

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Variables
- Basically, an assignment is an order

>>> 17 = n
File "<interactive input>", line 1
SyntaxError: can't assign to literal

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Variables
- We use variables in a program to “remember” things
- But variables are variable, means they can change over time
- You can assign a value to variable, and later assign a different value to the
same variable >>> day = "Thursday"
>>> day
'Thursday‘
>>> day = "Friday"
>>> day
'Friday'
>>> day = 21
>>> day
21

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Variable names : Rules for naming variables
- Variable names can formed using letters (A-Z) digits (0-9) and under score (_)
- But must begin with a letter or an underscore (Ex: sum or _sum)
- Must not begin with digit (Ex: 5sum Invalid variable name)
- Keywords cannot be used (Ex: class, str, int, float invalid variable names)
- Case sensitive (Upper case and lower case letters are distinct
(Ex: sum or Sum or SUM all are different )
- The underscore character ( _) can used in variable names with multiple words,
such as sum_of_numbers or average_on_sum
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Variable names : Rules for naming variables
- If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = "big parade"
SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = "Computer Science 101"
SyntaxError: invalid syntax
- 76trombones is illegal because it does not begin with a letter
- more$ is illegal because it contains an illegal character dollar sign
- class is one of the Python keywords, keywords cannot be used
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Keywords
- Python has thirty-something keywords

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Statements
- A statement is an instruction that the Python interpreter can execute
- When you type a statement on the command line Python executes it
- Statements don’t produce any result
- We have only seen the assignment statement so far

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Statements
A statement is an instruction that the Python interpreter can execute
- When you type a statement on the command line Python executes it
- Statements don’t produce any result
- We have only seen the assignment statement so far
- Some other kinds of statements are: while statements, for statements,
if statements, and import statements.

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Evaluating Expressions
- An expression is a combination of values, variables, operators, and calls to
functions
- If you type an expression at the Python prompt, the interpreter evaluates it and
displays the result:

>>> 1 + 1
2
>>> len("hello")
5

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Operators and operands
- Operators are special tokens that represent computations like addition,
multiplication and division
- The values the operator uses are called operands
- The tokens +, -, and *, and the use of parenthesis for grouping

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Operators and operands

* is for multiplication
20+32
** is for exponentiation
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Operators and operands
- Python gives us two different flavors of the division operator
1. In Python 3, the division operator / always yields a floating point result
2. Floor division uses the token //, its result is always a whole number
and if it has to adjust the number it always moves it to the left on the
>>> 7 / 4
number line 1.75
>>> 7 // 4
1
>>> minutes = 645
>>> hours = minutes // 60
>>> hours
10

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Type converter functions
- Python has type converter functions int( ), float( ) and str( )
- Which will convert their argument values into types int, float and str
respectively
- The int( ) function can take a floating point number or a string as
argument, and convert argument value into an int type
- For floating point numbers, it discards the decimal portion of the number
Process we call truncation towards zero on the number line

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Type converter functions
>>> int(3.14)
3
>>> int(3.9999) # This doesn't round to the closest int!
3
>>> int(3.0)
3
>>> int(-3.999) # Note that the result is closer to zero
-3
>>> int(minutes / 60)
10
>>> int("2345") # Parse a string to produce an int
2345
>>> int(17) # It even works if arg is already an int
17

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Type converter functions

- what do we expect?

>>> int("23 bottles")

Traceback (most recent call last):


File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10:
'23 bottles'

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Type converter functions
- The type converter function float( ) can convert an integer argument
into a float value
- Also convert syntactically legal string into a float value

>>> float(17)
17.0
>>> float("123.45")
123.45

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Type converter functions
- The type converter function str( ) can convert its argument into string value
- Also convert syntactically legal string into a float value

>>> str(17)
'17'
>>> str(123.45)
'123.45'

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Order of Operations
- When more than one operator appears in an expression, the order of
evaluation depends on the rules of precedence
- Python follows the same precedence rules for its mathematical operators that
mathematics does
- The acronym PEM-DAS is a useful way to remember the order of operations:

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Order of Operations
- Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want.
- Since expressions in parentheses are evaluated first
- EX: 2 * (3-1) is 4 # 3-1 evaluate first due to parentheses
- Exponentiation has the next highest precedence
- Ex: 2**1+1 is 3 #2**1 evaluate first

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Order of Operations
- Multiplication and Division operators have the same precedence, which is
higher than Addition and Subtraction
Ex: 2*3-1 # 2*1 evaluate first , then subtraction evaluates
- Operators with the same precedence are evaluated from left-to-right, they
are left-associative
- Ex: 6-3+2 # first 6-3 evaluates, then addition due to left-to-right associative

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Operations on String
- We cannot perform mathematical operations on strings
- The following are illegal
Ex:
>>> message - 1 # Error
>>> "Hello" / 123 # Error
>>> message * "Hello" # Error
>>> "15" + 2 # Error

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Operations on String
- But + operator work with strings
- The + operator represents concatenation, means joining the two operands
by linking them end-to-end.
Ex:
fruit = "banana"
baked_good = " nut bread"
print(fruit + baked_good)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Input
- The input() is built-in function in Python for getting input from the user
- Input() function returns entered value in string always

>>> name = input("Please enter country name: ")


Please enter country name: India
>>> name
'India'

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Input
- Input() function returns entered value in string always
>>> age = input("Please enter your age: ")
Please enter your age: 22
>>> age
'22'

- We need to convert string into int or float using the int() or float() converter
functions
>>> int(age)
22
>>> float(age)
22.0

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Composition
- Combining variables, expressions, statements and function calls into larger chunks

response = input("What is your radius? ")


r = float(response)
area = 3.14159 * r**2
print("The area is ", area)
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Composition

r = float( input("What is your radius? ") )


2 print("The area is ", 3.14159 * r**2)

or

print("The area is ", 3.14159*float(input("What is your radius?"))**2)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
The modulus operator
- The modulus operator works on integers
- Gives remainder when first number is divided by second number
- Percent sign (%) is used as modulus operator

>>> r = 7 % 3
>>> print( r )
1

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
The modulus operator

total_secs = int(input("How many seconds, in total?"))


hours = total_secs // 3600
secs_still_remaining = total_secs % 3600
minutes = secs_still_remaining // 60
secs_finally_remaining = secs_still_remaining % 60
print("Hrs=", hours, " mins=", minutes,"secs=", secs_finally_remaining)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: for statement Syntax:
for variable in list :
- for loop processes each item in a list <STATEMENT>
- Each item in turn is assigned to the loop variable, and then
body of the loop is executed

for friend in ["Joe", "Zoe", "Zuki", "Thandi", "Paris"]:


invite = "Hi " + friend + ". Please come to my party!"
print(invite)

- Running through all the items in a list is called traversing the list
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: for statement
Syntax:
for variable in list :
<STATEMENT>

numbers = [5, 6, 32, 21, 9]


running_total = 0
for number in numbers:
running_total = running_total + number
print(running_total)
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: for statement Syntax:
for variable in list :
Example: Generate Table <STATEMENT>
for x in range(13):
0 1
print(x, "\t", 2**x) 1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: while statement
Example-1:
Syntax n=6
while <CONDITION>: current_sum = 0
<STATEMENT>
i=0
while i <= n:
current_sum += i
i += 1
print(current_sum)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: while statement
Example-2:The Collatz 3n + 1 sequence
Syntax n = 1027371
while <CONDITION>: while n != 1:
<STATEMENT>
print(n, end=", ")
if n % 2 == 0:
n = n // 2
else:
n=n*3+1
print(n, end=".\n")
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: while statement
Example-3:Counting digits
Syntax

while <CONDITION>: n = 3029


<STATEMENT>
count = 0
while n != 0:
count = count + 1
n = n // 10
print(count)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: while statement
Example-3:Counting digits only 0 and 5
Syntax n = 2574301453
while <CONDITION>: count = 0
<STATEMENT> while n > 0:
digit = n % 10
if digit == 0 or digit == 5:
count = count + 1
n = n // 10
print(count)
Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: The break statement

- The break statement is used to immediately leave the


body of its loop
- The next statement to be executed is the first one after
the body

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: The break statement

for i in [12, 16, 17, 24, 29]:


if i % 2 == 1: # If the number is odd
break # ... immediately exit the loop
print(i)
print("done")

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Pre-test loops

- for and while loops do their tests at the beginning,


before executing any part of the body, called pre-test
loops

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Pre-test loops
- for and while
for i in []: # List is empty, immediately exit the loop
if i % 2 == 1:
break
print(i)
print("done")

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Pre-test loops
- for and while
num=-1
while(num>0):
print(num)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Middle-test loops

- Sometimes we’d like to have the middle-test loop with the exit
test in the middle of the body
- Python just uses a combination of while and if
<CONDITION>: break to get the job done

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Middle-test loops

- Sometimes we’d like to have the middle-test loop with the exit
test in the middle of the body
- Python just uses a combination of while and if
<CONDITION>: break to get the job done

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Middle-test loops

total = 0
while True:
response = input("Enter the next number. (Leave blank to end)")
if response == "" or response == "-1":
break
total += int(response)
print("The total of the numbers you entered is ", total)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Post-test loops

- Sometimes we’d like to have the post-test loop with the exit test
in the end of the body
- Moving the if condition: break to the end of the loop
body we create a pattern for a posttest loop
- Post-test loops are used when you want to be sure
that the loop body always executes at least once

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: Post-test loops
import random
rng = [Link]()
while True:
number=[Link](1,1000)
print('New random number is : '+str(number))
response = input("Play again? (yes or no)")
rng = [Link]()
if response != "yes":
break
print("Goodbye!")

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: The continue statement

- This is a control flow statement


- It skip the processing of the rest of the body of the loop, for the
current iteration
- But the loop still carries on running for its remaining iterations

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Iteration: The continue statement

for i in [12, 16, 17, 24, 29, 30]:


if i % 2 == 1:
continue
print(i)
print("done")

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Paired Data:

year_born = ("Paris Hilton", 1981)

celebs = [("Brad Pitt", 1963), ("Jack Nicholson", 1937),


("Justin Bieber", 1994)]

print(celebs)
print(len(celebs))

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Paired Data:

- Now we print the names of those celebrities born before 1980:

for name, year in celebs:


if year < 1980:
print(name)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Nested Loops for Nested Data:

- List of students: Each student has a name which is paired up


with another list of subjects that they are enrolled for:
students = [
("John", ["CompSci", "Physics"]),
("Vusi", ["Maths", "CompSci", "Stats"]),
("Jess", ["CompSci", "Accounting", "Economics", "Management"]),
("Sarah", ["InfSys", "Accounting", "Economics", "CommLaw"]),
("Zuki", ["Sociology", "Economics", "Law", "Stats", "Music"])]

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Nested Loops for Nested Data:

- Let’s print out each student name, and the number of subjects
they are enrolled for:

for name, subjects in students:


print(name, "takes", len(subjects), "courses")

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Nested Loops for Nested Data:
- Now we’d like to ask how many students are taking CompSci?
- This needs a counter, and for each student we need a
second loop that tests each of the subjects in turn:
counter = 0
for name, subjects in students:
for s in subjects: # A nested loop!
if s == "CompSci":
counter += 1
print("The number of students taking CompSci is", counter)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Algorithms:
- Algorithm is a mechanical process for solving a category of problems
- Hard problems can be solved by step-by-step algorithmic processes
Ex: Newton’s method for finding square roots
better = (approximation + n/approximation)/2
n=8
threshold = 0.001
approximation = n/2
while True:
better = (approximation + n/approximation)/2
if abs(approximation - better) < threshold:
print(better)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Function: That require arguments
- Function is a named sequence of statements that belong
- Most functions require arguments
- Arguments provide data to function for generalization
- Python has a built-in function for computing the absolute value

Ex:
>>> abs(5) #abs function need single argument/parameter
5
>>> abs(-5)
5

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Function: That require arguments
- Some functions take more than one argument

Ex:
>>> pow(2, 3) #pow function need two arguments/parameters
8
>>> max(7, 11) #max function need two or more arguments/parameters
11
>>> max(4, 1, 17, 2, 12)
17
>>> max(3 * 11, 5**3, 512 - 9, 1024**0)
503

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Function: That return a values
- Calling each of these functions generates a value
- Assign that value to a variable or use as part of an expression

Ex:
biggest = max(3, 7, 2, 5)
2 x = abs(3 - 11) + 10

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga
Variables, expressions and statements
Function: That return a values
Ex:
def final_amount(p, r, n, t):
a = p * (1 + r/n) ** (n*t)
return a # Function return the computed result

toInvest = float(input("How much do you want to invest?"))


fnl = final_amount(toInvest, 0.08, 12, 5)
print("At the end of the period you'll have", fnl)

Aruna Kumar P
Dept. of ISE, JNNCE, Shivamogga

You might also like