0% found this document useful (0 votes)
12 views49 pages

Python Input and Output Basics

The document provides an overview of input and output in Python, explaining how to use the print and input functions. It discusses the difference between strings and numeric types, the concept of variables, and how to handle user input, including potential errors. Additionally, it covers string manipulation techniques and basic math operations in Python.

Uploaded by

farragamr730
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)
12 views49 pages

Python Input and Output Basics

The document provides an overview of input and output in Python, explaining how to use the print and input functions. It discusses the difference between strings and numeric types, the concept of variables, and how to handle user input, including potential errors. Additionally, it covers string manipulation techniques and basic math operations in Python.

Uploaded by

farragamr730
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

1

Outlines
• Input output
• Strings
• Container types
• Lists
• Dictionaries
Input and Output
Output
• Output is text that is printed to the screen
– So the user can see it

• The command for this is print


– Use the keyword “print” and put what you
want to be displayed in parentheses after it
Output Example
print (3 + 4)
print (3, 4, 3 + 4)
print()
print("The answer is", 3 + 4)

7 What does this


3 4 7 output to the screen?

The answer is 7
Output Exercise 1
• What will the following code snippet print?
a = 10
b = a * 5
c = "Your result is:"
print(c, b)

Your result is: 50


Output Exercise 2
• What will the following code snippet print?
a = 10
b = a
a = 3
There are a few possible
print(b) options for what this
could do! Any guesses?
10
Output Exercise 2 Explanation
• Why does it print out 10?

• When you set one variable equal to another,


they don’t become linked!
– They are separate copies of a value

• After b is set to 10, it no longer


has anything else to do with a
Output Exercise 2 Explanation
a = 10
b = a
a = 3
print(b)

10
Output Exercise 2 Explanation
a = 10
b = a
a = 3
print(b)

10 10
Output Exercise 2 Explanation
a = 10
b = a
a = 3
print(b)

130 10
Output Exercise 2 Explanation
a = 10
b = a
a = 3
print(b)
output: 10
3 10
Input
• Input is information we get from the user
– We must tell them what we want first

userNum = input("Please enter a number: ")


print(userNum)

• The input and output will look like this:


Please enter a number:
22 22
How Input Works

userNum = input("Please enter a number: ")


• Takes the text the user entered and stores it
In the variable named userNum

• You can do this as many times as you like!


userNum = input("Enter another number: ")
userNum2 = input("Enter a new number: ")
userAge = input("Please enter your age: ")
Input as a String
• Everything that is stored via input()
will come through in the form of a string

• There is a difference between "10" and 10


– "10" is a string containing two characters
– 10 is understood by Python as a number
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
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
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
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
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>w
>>hatever the user types is then stored as a string
• – What happens if the user inputs a number?
Assigning Input

• Here is a sample interaction with the Python


interpreter:
>>> number = input("Enter a
number: ")
Enter a number: 3
Still a string! >>> number
'3'

• How can we >fo


>>rce 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
Assigning Input
• Here is a sample interaction with the Python
interpreter:
>>> number =
eval(input("Enter a number:
"))
Enter a number: 3
Now an int
>>> number
(no single quotes)!
3
>>>
Assigning Input
• Here is a sample interaction with the Python
interpreter:
>>> number =
eval(input("Enter a number:
"))
Enter a number: 3.7
And now a float
>>> number
(no single quotes)!
3.7
>>>
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”
print
• print : Produces text output on the console.
• Syntax:
print "Message"
print Expression
– Prints the given text message or expression value on the
console, and moves the cursor down to the next line.
print Item1, Item2, ..., ItemN
– Prints several messages and/or expressions on the same
line.
input
• input : Reads a number from user input.
– You can assign (store) the result of input into a
variable.
– Example:
age = input("How old are you? ")
print "Your age is", age
print "You have", 65 - age, "years
until retirement"
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
Program Example
• Find the area of a circle given the radius:

• Radius = 10
• pi = 3.14159
• area = pi * Radius * Radius
• print( area )

• will print 314.15 to the screen.


Input/Output
● Input functions (input()) allow users of a
program to place values into programming
code.
○ The parameter for an input function is
called a prompt. This is a string (this can
be indicated by “” or „‟) such as “Enter a
number: “

○ The user‟s response to the prompt will


be returned to the input statement call as
a string. To use this value as any other
data type, it must be converted with
another function (int()).
xString = input(“Enter a number:
● Print functions (print()) allow programs to
x = int(xString)
output strings to users on a given interface. y=x+2
print(y)
○ The parameter of this function is of any
type. All types will automatically be
converted to strings.
Getting input from the User
Your program will be more interesting if we
obtain some input from the user.
But be careful! The user may not always give
you the input that you wanted, or expected!
A function that is useful for getting input from
the user is:

input(<prompt string>) - always


returns a string

You must convert the string to a float/int if


you want to do math with it!
Input Example – possible errors from
the input() function
• userName = input(“What is your
name?”)
• userAge = int( input(“How old are
you?”) )
• birthYear = 2007 - userAge
• print(“Nice to meet you, “ +
userName)
• print(“You were born in: “,
birthYear)
input() is guaranteed to give us a string, no
matter WHAT the user enters.
But what happens if the user enters “ten” for
their age instead of 10?
Input Example – possible errors from the input() function
• userName = raw_input(“What is your
name?”)
• userAge = input(“How old are you?”)
• try:
• userAgeInt = int(userAge)
• except:
• userAgeInt = 0
• birthYear = 2010 - userAgeInt
• print(“Nice to meet you, “ + userName)
• if userAgeInt != 0:
• print(“You were born in: “,
birthYear )

The try/except statements protects us if the user enters


something other than a number. If the int() function is
unable to convert whatever string the user entered, the except clause will set the
userIntAge variable to zero.
Real numbers
• Python can also manipulate real numbers.
– Examples: 6.022 -15.9997 42.0
2.143e17

• The operators + - * / % ** ( ) all work for real numbers.


– The / produces an exact answer: 15.0 / 2.0 is 7.5
– The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
Math commands
• Python has useful commands for performing calculations.

• To use many of these commands, you must write the following at the
top of your Python program:
Constant Description
from math import *
e 2.7182818...
Command name Description
pi 3.1415926...
abs(value) absolute value
ceil(value) rounds up
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
128
Garbage Collection
• Interestingly, as a Python programmer you do
not have to worry about computer memory
getting filled up with old valuesAfter
when new
values are assigned to variables Memory locatio
Xwill be automati
reclaimed by the
• Python will automatically clear old garbage collecto
values out of memory in a pro cess
known as garbage collection
The Basics
Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" True # comparison
• "e" in "hello" True # search
More on Strings
• Strings can be subscripted (indexed)
• Like in C, the first character of a string has subscript (index) 0.
• There is no separate character type;
• A character is simply a string of size one.
• An omitted first index defaults to zero, an omitted second index defaults to the size of the
string being sliced
>>> “hello”[:2] „he' # The first two characters
>>> “hello”[2:] „llo‟ #Except the first two characters

H E L L O
0 1 2 3 4
-5 -4 -3 -2 -1

Indices may be negative numbers, to start counting from the right. For example:
>>> “hello”[-1] „0' # The last character
>>> “hello”[-2] „l' # Last but one character
>>> “hello”[-2:] „lo' # The last two characters
>>> “hello”[:-2] „hel' # Except the last two characters
Using Escape Sequences with Strings
▪ Escape sequence: Set of characters that allow you to insert
special characters into a string
▪ Backslash followed by another character
▪ e.g. \n
▪ Simple to use

8
Escape Sequences
▪ System bell
▪ print ("\a”)
▪ Tab
▪ print ("\t\t\tFancy Credits”)
▪ Backslash
▪ print ("\t\t\t \\ \\ \\ \\ \\ \\ \\”)
▪ Newline
▪ print ("\nSpecial thanks goes out to:”)
▪ Quote
▪ print ("My hair stylist, Henry \'The Great\', who never says
\"can\'t\".”) 10
Escape Sequences (continued)

41
Concatenating and Repeating Strings
▪ Can combine two separate strings into larger one
▪ Can repeat a single string multiple times

42
Concatenating Strings
▪ String concatenation: Joining together of two strings to form a new string
▪ When used with string operands, + is the string concatenation operator
▪ "concat" + "enate"
▪ Suppressing a Newline
▪ When used at the end of print statement, comma suppresses newline
▪ print "No newline after this string",

43
Repeating String
▪ Multiple concatenations
▪ When used with strings, * creates a new string by concatenating a string a specified number of
times
▪ Like ―multiplying‖ a string
▪ "Pie" * 10 creates new string "PiePiePiePiePiePiePiePiePiePie"

44
Using String Methods
▪ String methods allow you to do many things, including:
▪ Create new strings from old ones
▪ Create string that’s all-capital-letters version of original
▪ Create new string from original, based on letter substitutions

45
String Methods
▪ Method: A function that an object has
▪ Use dot notation to call (or invoke) a method
▪ Use variable name for object, followed by dot, followed by method name and parentheses
▪ an_object.a_method()
▪ Strings have methods that can return new strings

18
String Methods
(continued)
▪ quote = "I think there is a world market for maybe
five computers."
▪ print ([Link]())
I THINK THERE IS A WORLD MARKET FOR MAYBE FIVE COMPUTERS.
▪ print ([Link]())
i think there is a world market for maybe five computers.
▪ print ([Link]())
I Think There Is A World Market For Maybe Five Computers.
▪ print ([Link]("five", "millions of"))
I think there is a world market for millions of computers.

▪ Original string unchanged


▪ print (quote)
19
I think there is a world market for maybe five computers.
String Methods (continued)

20
Container
Types
Python Supports several Container types

➢ Lists
➢ Tuples
➢ Sets
➢ Dictionaries

You might also like