Chuỗi, rẽ nhành và lặp

Ôn tập về phép toán gán

In [1]:
x = 2
x = x * x
y = x + 1
print('x =', x)
print('y =', y)
x = 4
y = 5
In [2]:
# Swap variables - NOT DO
x = 1
y = 2
y = x
x = y
print('x =', x)
print('y =', y)
x = 1
y = 1
In [3]:
# Swap variables - DO
x = 1
y = 2
temp = y
y = x
x = temp
print('x =', x)
print('y =', y)
x = 2
y = 1

Chuỗi ký tự (String)

In [4]:
hi = "hello there"
greetings = 'hello'

foo = "this isn't right"

name = 'eric'
greet = hi + name
greeting = hi + ", " + name

print(greet)
print(greeting)
hello thereeric
hello there, eric

Toán tử trên chuỗi

In [5]:
'ab' + 'cd'
Out[5]:
'abcd'
In [6]:
3 * 'eric'
Out[6]:
'ericericeric'
In [7]:
len('eric')
Out[7]:
4
In [8]:
len('hi there')
Out[8]:
8
In [9]:
'eric'[1]
Out[9]:
'r'
In [10]:
'eric'[0]
Out[10]:
'e'
In [11]:
name = 'eric'
name[0]
Out[11]:
'e'
In [12]:
name[4]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-12-766a7f505528> in <module>()
----> 1 name[4]

IndexError: string index out of range
In [13]:
'eric'[1:3]
Out[13]:
'ri'
In [14]:
'eric'[:3]
Out[14]:
'eri'
In [15]:
'eric'[1:]
Out[15]:
'ric'
In [16]:
'eric'[:]
Out[16]:
'eric'

Xuất, nhập dữ liệu

In [17]:
x = 1
print(x)
x_str = str(x)
print("my fav num is", x, ".", "x = ", x)
print("my fav num is" + x_str + "." + "x = " + x_str)
print("my fav num is " + x_str + ". " + "x = " + x_str)
1
my fav num is 1 . x =  1
my fav num is1.x = 1
my fav num is 1. x = 1
In [18]:
text = input("Type something...")
print(5 * text)
type(text)
Type something...hello
hellohellohellohellohello
Out[18]:
str
In [19]:
num = int(input("Type a number..."))
print(5 * num)
Type a number...10
50

Lệnh lặp

In [20]:
n = input('You are in the Lost Forest. Go left or right?')
while n == 'right':
    n = input('You are in the Lost Forest. Go left or right?')
print('You got out of the Lost Forest!')
You are in the Lost Forest. Go left or right?right
You are in the Lost Forest. Go left or right?right
You are in the Lost Forest. Go left or right?left
You got out of the Lost Forest!
In [ ]:
####################
## EXAMPLE: while loops 
## Try expanding this code to show a sad face if you go right
## twice and flip the table any more times than that.
## Hint: use a counter
####################
#n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
#while n == "right" or n == "Right":
#    n = input("You are in the Lost Forest\n****************\n******       ***\n  (╯°□°)╯︵ ┻━┻\n****************\n****************\nGo left or right? ")
#print("\nYou got out of the Lost Forest!\n\o/")
In [21]:
n = 0
while n < 5:
    print(n)
    n = n + 1
0
1
2
3
4
In [22]:
for n in range(5):
    print(n)
0
1
2
3
4
In [23]:
mysum = 0
for i in range(7, 10):
    mysum += i
print(mysum)
24
In [24]:
mysum = 0
for i in range(5, 11, 2):
    mysum += i
print(mysum)
21
In [25]:
mysum = 0
for i in range(5, 11, 2):
    mysum += i
    if mysum == 5:
        break
print(mysum)
5
In [26]:
total = 0
for c in '123456789':
    total = total + int(c)
print(total)
45
In [27]:
x = 3
ans = 0
itersLeft = x
while (itersLeft != 0):
    ans = ans + x
    itersLeft = itersLeft - 1
print(str(x) + '*' + str(x) + ' = ' + str(ans))
3*3 = 9

Bài tập

Replace the comment in the following code with a while loop.

In [28]:
numXs = int(input('How many times should I print the letter X? '))
toPrint = ''
#concatenate X to toPrint numXs times
print(toPrint)
How many times should I print the letter X? 4

Bài tập

Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered, it should print a message to that effect.

In [ ]:
 

Thử, sai (Guess and check)

In [29]:
# Find a cube root of x
x = int(input('Enter an integer: '))
ans = 0
while ans ** 3 < x:
    ans = ans + 1
if ans ** 3 != x:
    print(str(x) + ' is not a perfect cube')
else:
    print('Cube root of ' + str(x) + ' is ' + str(ans))
Enter an integer: 27
Cube root of 27 is 3
In [30]:
# Find a cube root of x
x = int(input('Enter an integer: '))
ans = 0
while ans ** 3 < abs(x):
    ans = ans + 1
if ans ** 3 != abs(x):
    print(str(x) + ' is not a perfect cube')
else:
    if x < 0:
        ans = -ans
    print('Cube root of ' + str(x) + ' is ' + str(ans))
Enter an integer: 29
29 is not a perfect cube
In [31]:
cube = 27
for guess in range(cube + 1):
    if guess**3 == cube:
        print('Cube root of', cube, 'is', guess)
Cube root of 27 is 3
In [32]:
cube = 8
for guess in range(abs(cube) + 1):
    if guess**3 >= abs(cube):
        break
if guess**3 != abs(cube):
    print(cube, 'is not a perfect cube')
else:
    if cube < 0:
        guess = -guess
    print('Cube root of ' + str(cube) + ' is ' + str(guess))
Cube root of 8 is 2

Bài tập

Write a program that asks the user to enter an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer entered by the user. If no such pair of integers exists, it should print a message to that effect.

In [ ]:
 

Bài tập

Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in s.

In [ ]: