1 Python Values and Variables
1 Python Values and Variables
>>>x = input()
>>>print('Text entered:', x)
My name is Rick
Text entered: My name is Rick
6. User Input (2/3)
The input function produces only strings, but we can use the
int function to convert a properly formed string of digits into an
integer.
>>>x = input()
>>>y = input()
>>>num1 = int(x)
>>>num2 = int(y)
>>>print(num1, '+', num2, '=', num1 + num2) 2
17
2 + 17 = 19
6. User Input (3/3)
For float numbers:
>>> num = int(float(input('Please enter a number: ')))
Please enter a number: 3
>>> num
3
>>> num = int(float(input('Please enter a number: ')))
Please enter a number: 3.4
>>> num
3
What if you wish to round the user’s input value instead of truncating it?
the statement
print()
is a shorter way to express
print(end='\n')
7. Controlling the print
Function (3/4)
>>>print('A', end=‘’)
>>>print('B', end=‘’)
>>>print('C', end=‘’)
ABC
7. Controlling the print
Function (4/4)
By default, the print function places a single space in between the items it prints.
print uses a keyword argument named sep to specify the string to use insert between items.
The name sep stands for separator.
The default value of sep is the string ' ', a string containing a single space.
0 1
1 10
2 100
3 1000
4 10000
5 100000
8. String Formatting (2/2)
print('{0} {1}'.format(0, 10**0))
print('{0} {1}'.format(1, 10**1))
print('{0} {1}'.format(2, 10**2))
print('{0} {1}'.format(3, 10**3))
print('{0} {1}'.format(4, 10**4))
print('{0} {1}'.format(5, 10**5))
Has the same formatting as previous slide
9.Multi-line Strings
A Python string ordinarily spans a single line of text. The following statement is illegal:
x = 'This is a long string with
several words’
Python provides way to represent a string’s layout more naturally within source code, using triple
quotes.
The triple quotes (''' or """) delimit strings that can span multiple lines in the source code.
>>>x = '''
This is a multi-line
string that goes on
for three lines! This is a multi-line
‘‘’ string that goes on
for three lines!
>>>print(x)
Python
Values and Variables