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

Lecture-9-InputOutput

The document covers the basic elements of Python programming, including literals, assignment statements, input handling, datatype conversion, and identifiers. It explains how to use literals in print functions, assign values to variables, and convert user input into different data types. Additionally, it discusses simultaneous assignment and the rules for forming valid identifiers in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture-9-InputOutput

The document covers the basic elements of Python programming, including literals, assignment statements, input handling, datatype conversion, and identifiers. It explains how to use literals in print functions, assign values to variables, and convert user input into different data types. Additionally, it discusses simultaneous assignment and the rules for forming valid identifiers in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Principles of Computing

Basic Elements of Python Programs

By Dr. Joydeep Chandra


Indian Institute of Technology, Patna

25/08/23 1 Indian Institute of Technology Patna


Today…

• Last Class:
• Motivation
• Introduction to Hardware Basics & Programming
Languages
• Writing Simple Python Commands

• Today’s Class:
• Basic Elements of Python Programs: Literals,
Assignments, Datatype Conversion, Identifiers, and
Expressions

25/08/23 2 Indian Institute of Technology Patna


Literals
• In the following example, the parameter values
passed to the print function are all technically
called literals
• More precisely, “Hello” and “Programming is fun!” are
called textual literals, while 3 and 2.3 are called
numeric literals

>>> print("Hello")
Hello
>>> print("Programming is fun!")
Programming is fun!
>>> print(3)
3
>>> print(2.3)
2.3

25/08/23 3 Indian Institute of Technology Patna


Simple Assignment Statements

• A literal is used to indicate a specific value, which


can be assigned to
a variable >>> x = 2
x is a variable and 2 is its value >>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3

25/08/23 4 Indian Institute of Technology Patna


Simple Assignment Statements

• A literal is used to indicate a specific value, which


can be assigned to
a variable >>> x = 2
x is a variable and 2 is its value >>> print(x)
2
 x can be assigned different values;
>>> x = 2.3
hence, it is called a variable >>> print(x)
2.3

25/08/23 5 Indian Institute of Technology Patna


Simple Assignment Statements: Box View

• A simple way to view the effect of an assignment


is to assume that when a variable changes, its old
value is replaced
>>> x = 2 x = 2.3
Before After
>>> print(x)
2 x 2 x 2.3
>>> x = 2.3
>>> print(x)
2.3

25/08/23 6 Indian Institute of Technology Patna


Simple Assignment Statements: Actual View

• Python assignment statements are actually


slightly different from the “variable as a box”
model
• In Python, values may end up anywhere in memory,
and variables are used to refer to them
x = 2.3
>>> x = 2 After
Before
>>> print(x) What will
2 2 happen to
x 2 x
>>> x = 2.3 value 2?
>>> print(x)
2.3
2.3

25/08/23 7 Indian Institute of Technology Patna


Garbage Collection
• Interestingly, as a Python programmer you do not have
to worry about computer memory getting filled up with
old values when new values are assigned to variables

• Python will automatically clear old


values out of memory in a After
Memory location
process known as
garbage collection
x 2
X will be
automatically
reclaimed by the
garbage collector
2.3

25/08/23 8 Indian Institute of Technology Patna


Assigning Input

• So far, we have been using values specified by programmers and


printed or assigned to variables
• How can we let users (not programmers) input values?

• In Python, input is accomplished via an assignment statement


combined with a built-in function called input
<variable> = input(<prompt>)

• When Python encounters a call to input, it prints <prompt> (which


is a string literal) then pauses and waits for the user to type some
text and press the <Enter> key

25/08/23 9 Indian Institute of Technology Patna


Assigning Input
• Here is a sample interaction with the Python
interpreter:
>>> name = input("Enter your name:
")
Enter your name: Mohammad
Hammoud
>>> name
'Mohammad Hammoud'
>>>

• Notice that whatever the user types is then stored


as a string
• What happens if the user inputs a number?

25/08/23 10 Indian Institute of Technology Patna


Assigning Input
• Here is a sample interaction with the Python interpreter:

>>> number = input("Enter a number:


")
Enter a number: 3
>>> number
Still a string! '3'
>>>

• How can we force an input number to be stored as a


number and not as a string?
• We can use the built-in eval function, which can be “wrapped
around” the
input function

25/08/23 11 Indian Institute of Technology Patna


Assigning Input

• Here is a sample interaction with the Python


interpreter:
>>> number = eval(input("Enter a
number: "))
Enter a number: 3
>>> number
Now an int
3
(no single quotes)!
>>>

25/08/23 12 Indian Institute of Technology Patna


Assigning Input

• Here is a sample interaction with the Python


interpreter:
>>> number = eval(input("Enter a
number: "))
Enter a number: 3.7
>>> number
And now a float
3.7
(no single quotes)!
>>>

25/08/23 13 Indian Institute of Technology Patna


Assigning Input

• Here is another sample interaction with the


Python interpreter:
>>> number = eval(input("Enter an equation:
"))
Enter an equation: 3 + 2
>>> number
5
>>>

The eval function will evaluate this formula and


return a value, which is then assigned to the variable “number”

25/08/23 14 Indian Institute of Technology Patna


Datatype Conversion

• Besides, we can convert the string output of the


input function into an integer or a float using the
built-in int and float functions
>>> number = int(input("Enter a number:
"))
Enter a number: 3
An integer >>> number
(no single quotes)! 3
>>>

25/08/23 15 Indian Institute of Technology Patna


Datatype Conversion

• Besides, we can convert the string output of the


input function into an integer or a float using the
built-in int and float functions
>>> number = float(input("Enter a number:
"))
Enter a number: 3.7
A float >>> number
(no single quotes)! 3.7
>>>

25/08/23 16 Indian Institute of Technology Patna


Datatype Conversion

• As a matter of fact, we can do various kinds of


conversions between strings, integers and floats
using the built-in int, float, and str functions

>>> x = 10 >>> y = >>> z =


>>> "20" 30.0
float(x) >>> >>> int(z)
10.0 float(y) 30
>>> str(x) 20.0 >>> str(z)
'10' >>> int(y) '30.0'
>>> 20 >>>
>>>

integer  float string  float float  integer


integer  string string  integer float  string

25/08/23 17 Indian Institute of Technology Patna


Simultaneous Assignment

• Python allows us also to assign multiple values to multiple


variables all at the same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
>>>

• This form of assignment might seem strange at first, but it can


prove remarkably useful (e.g., for swapping values)

25/08/23 18 Indian Institute of Technology Patna


Simultaneous Assignment

• Suppose you have two variables x and y, and you


want to swap their values (i.e., you want the value
stored in x to be in y and vice versa)

>>> x = 2
>>> y = 3
>>> x = y
X CANNOT be done with
two simple assignments

>>> y = x
>>> x
3
>>> y
3

25/08/23 19 Indian Institute of Technology Patna


Simultaneous Assignment

• Suppose you have two variables x and y, and you


want to swap their values (i.e., you want the value
stored in x to be in y and vice versa)
>>> x = 2
Thus far, we have been >>> y = 3
using >>> temp = x CAN be done with
different names for >>> x = y three simple assignments,
variables. These names
are technically called
>>> y = temp
>>> x
 but more efficiently with
simultaneous assignment
identifiers 3
>>> y
2
>>>

25/08/23 20 Indian Institute of Technology Patna


Identifiers
• Python has some rules about how identifiers
can be formed
• Every identifier must begin with a letter or
underscore, which may be followed by any sequence
of letters, digits, or underscores
>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
File "<stdin>", line 1
2celsius
^
SyntaxError: invalid syntax

25/08/23 21 Indian Institute of Technology Patna


Identifiers

• Python has some rules about how identifiers


can be formed
• Identifiers are case-sensitive

>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7

25/08/23 22 Indian Institute of Technology Patna


Identifiers
• Python has some rules about how identifiers
can be formed
• Some identifiers are part of Python itself (they are
called reserved words or keywords) and cannot be
used by programmers as ordinary identifiers
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Python Keywords

25/08/23 23 Indian Institute of Technology Patna


Identifiers
• Python has some rules about how identifiers
can be formed
• Some identifiers are part of Python itself (they are
called reserved words or keywords) and cannot be
used by programmers as ordinary identifiers

>>> for = 4
File "<stdin>", line 1
An example… for = 4
^
SyntaxError: invalid syntax

25/08/23 24 Indian Institute of Technology Patna


Expressions

• You can produce new data (numeric or text)


values in your program using expressions
>>> x = 2 + 3
 This is an expression that uses the
>>> print(x)
addition operator 5
>>> print(5 * 7)
35
>>> print("5" + "7")
57

25/08/23 25 Indian Institute of Technology Patna


Expressions

• You can produce new data (numeric or text)


values in your program using expressions

>>> x = 2 + 3
 This is an expression that uses the
>>> print(x)
addition operator 5
>>> print(5 * 7)
 This is another expression that uses the
35
multiplication operator >>> print("5" + "7")
57

25/08/23 26 Indian Institute of Technology Patna


Expressions

• You can produce new data (numeric or text)


values in your program using expressions
>>> x = 2 + 3
 This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
 This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
 This is yet another expression that uses the
addition operator but to concatenate (or glue)
strings together

25/08/23 27 Indian Institute of Technology Patna


Expressions

• You can produce new data (numeric or text)


values in your program using expressions
>>> x = 6 >>> print(x*y)
>>> y = 2 12
>>> print(x - y) >>> print(x**y)
Another 4 Yet another 36
example… >>> print(x/y) example… >>> print(x%y)
3.0 0
>>> print(x//y) >>> print(abs(-x))
3 6

25/08/23 28 Indian Institute of Technology Patna


Expressions: Summary of Operators

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Float Division
** Exponentiation
abs() Absolute Value
// Integer Division
% Remainder

Python Built-In Numeric Operations

25/08/23 29 Indian Institute of Technology Patna


Explicit and Implicit Data Type Conversion

• Data conversion can happen in two ways in Python


1. Explicit Data Conversion (we saw this earlier with the int, float, and
str
built-in functions)

2. Implicit Data Conversion


• Takes place automatically during run time between ONLY numeric values
• E.g., Adding a float and an integer will automatically result in a float value
• E.g., Adding a string and an integer (or a float) will result in an error since string
is not numeric
• Applies type promotion to avoid loss of information
• Conversion goes from integer to float (e.g., upon adding a float and an integer)
and not vice versa so as the fractional part of the float is not lost

25/08/23 30 Indian Institute of Technology Patna


Implicit Data Type Conversion: Examples

 The result of an expression that involves >>> print(2 + 3.4)


5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
>>> print(9/5 * 27 + 32)
80.6
>>> print(9//5 * 27 + 32)
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>

25/08/23 31 Indian Institute of Technology Patna


Implicit Data Type Conversion: Examples

 The result of an expression that involves >>> print(2 + 3.4)


5.4
a float number alongside (an) integer
>>> print( 2 + 3)
number(s) is a float number
5
 The result of an expression that involves >>> print(9/5 * 27 + 32)
80.6
values of the same data type will not result
>>> print(9//5 * 27 + 32)
in any conversion
59
>>> print(5.9 + 4.2)
10.100000000000001
>>>

25/08/23 32 Indian Institute of Technology Patna


Write down a python program to take input of two numbers, print the addition,
subtraction, and multiplication results.

# Input
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Addition
sum_result = num1 + num2
print("Addition result:", sum_result)

# Subtraction
sub_result = num1 - num2
print("Subtraction result:", sub_result)

# Multiplication
mul_result = num1 * num2
print("Multiplication result:", mul_result)
25/08/23 33 Indian Institute of Technology Patna
Write down a python program to take input of two numbers in
two different integers, swap them and print
# Input
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))

# Swapping values using a temporary variable


temp = num1
num1 = num2
num2 = temp

# Printing the swapped values


print("After swapping:")
print("First integer:", num1)
print("Second integer:", num2)

25/08/23 34 Indian Institute of Technology Patna


Modules

• One problem with entering code interactively into a Python shell


is that the definitions are lost when we quit the shell
• If we want to use these definitions again, we have to type them all over
again!

• To this end, programs are usually created by typing definitions


into a separate file called a module or script
• This file is saved on disk so that it can be used over and over again

• A Python module file is just a text file with a .py extension, which
can be created using any program for editing text (e.g., notepad
or vim)

25/08/23 35 Indian Institute of Technology Patna


Programming Environments and IDLE

• A special type of software known as a programming


environment simplifies the process of creating
modules/programs

• A programming environment helps programmers write


programs and includes features such as automatic indenting,
color highlighting, and interactive development

• The standard Python distribution includes a programming


environment called IDLE that you can use for working on the
programs of this course

25/08/23 36 Indian Institute of Technology Patna


Summary

• Programs are composed of statements that are built from


identifiers and expressions

• Identifiers are names


• They begin with an underscore or letter which can be followed by a
combination of letter, digit, and/or underscore characters
• They are case sensitive

• Expressions are the fragments of a program that produce data


• They can be composed of literals, variables, and operators

25/08/23 37 Indian Institute of Technology Patna


Summary

• A literal is a representation of a specific value (e.g., 3 is a


literal representing the number three)

• A variable is an identifier that stores a value, which can


change (hence, the name variable)

• Operators are used to form and combine expressions into


more complex expressions (e.g., the expression x + 3 * y
combines two expressions together using the + and *
operators)

25/08/23 38 Indian Institute of Technology Patna


Summary

• In Python, assignment of a value to a variable is done using the


equal sign (i.e., =)

• Using assignments, programs can get inputs from users and


manipulate them internally

• Python allows simultaneous assignments, which are useful for


swapping values of variables

• Datatype conversion involves converting implicitly and explicitly


between various datatypes, including integer, float, and string

25/08/23 39 Indian Institute of Technology Patna


Next Lecture…

• Functions- Part I

25/08/23 40 Indian Institute of Technology Patna

You might also like