课程:
Microsoft: DEV236x
Introduction to Python: Absolute Beginner
课时:
MOD04_1-7.2_Intro_Python.ipynb
习题:
Task 1
while with comparison operator
Program: Animal Names
Use while to get the user input, animal_name, of 4 animals
use a counter, num_animals, in the while loop condition
append the names to a string variable, all_animals
User can exit early by typing “exit” (check if animal_name is “exit” and break)
when the loop finishes, print the names of all_animals
-bonus: print “no animals” if animal_name is empty after exiting the loop
Tip: Think about Sequence and variables that need to be initialized before the while loop
解答:
前面还比较好出来,但是想要最后全部打印出来所有的input,意识没有想到好的办法
num_animals = 4
while num_animals > 0:
animal_name = input("What is your favourite animal?(use exit for finishing)")
if animal_name.lower().startswith("e") is True:
print("no animal.")
break
else:
print("Your favourite animal is", animal_name)
然后我想到了之前的习题里有这样的题目:
num_1 = ""
num_temp = ""
num_final = ""
while True:
num_1 = input("Enter an integer: ")
if num_1.isdigit():
num_final = num_temp + num_1
num_temp = num_final
else:
print(num_final)
break
这里的num_final = num_temp + num_1给了我启示
于是我设置了一个animal_temp
但是我又在这里卡住了,因为会进行4次询问,难道要设置4个temp吗?整个人就此钻到牛角尖里去了…
然后在课程的disscusion里面有看到说,可以把这个打印所有的功能表示成
all_animals = all_animals + animal_name
才恍然大悟
实际上我自己在想的时候已经走到快要最后一步了,然而还是没能自己想通…
其实我也有想过要不要弄一个list来展示,但是从课程的角度上来说是不可能让我们用list来做的,因为还没教…
好可惜哦,这道题最后还是没能全靠自己解出来!
最后解答:
animal_name = ""
all_animals = ""
num_animals = 4
while num_animals > 0:
animal_name = input("What is your favourite animal?(use exit for finishing)")
if animal_name.lower().startswith("e") is True:
print("no animal.")
break
else:
print("Your favourite animal is", animal_name)
all_animals = animal_name + " , " + all_animals
num_animals -= 1
print(all_animals)