Python自学记录 - 002

课程:
Microsoft: DEV236x
Introduction to Python: Absolute Beginner
课时:
MOD04_1-7.2_Intro_Python.ipynb

习题:
Task 2
Using while with a Boolean String
Program: Long Number
Create variables
int_num and get user input string of only digits
long_num and initialize it as an empty string
Create a while loop that runs as long as the input is all digits
Inside the while loop
add int_num to the end of long_num
get user input for int_num again (inside while loop this time)
After the loop exits
print the value of long_num

这里我先写出来的代码是这样子的:

#  create variables: int_num, long_num
int_num = ""
long_num = ""

while int_num.isdigit() != True:
    int_num = input("Enter only digits: ")
    long_num = long_num + int_num

print(long_num)

然后我在vscode上跑了一次,发现没有实现重复循环,也就是get user input for int_num again (inside while loop this time)这个要求,琢磨了一下,想到的是在while loop里面long_num后面增加一个int_num = input("Enter another only digits: ")
可是如果这么做,又满足不了add int_num to the end of long_num的要求
于是最后又想到了

#  create variables: int_num, long_num
int_num = ""
long_num = ""

while int_num.isdigit() != True:
    int_num = input("Enter only digits: ")
while int_num.isdigit() == True:
    int_num = input("Enter only digits: ")
    long_num = long_num + int_num


print(long_num)

但是这样写,最后的long_num打印不出来…
要设置循环次数吗?我觉得这个不是题目的本意…
于是去翻看discussion,发现教员AmitS_Lex (Staff)的解答是
H there, as per the instructions, while loop should run as long as the input is all digits, but your code is not doing the same. Please check below code for your referrence.

int_num = input("Enter digits ")

long_num = ""

while int_num.isdigit() == True:

 long_num = long_num + int_num

 int_num = input("Enter digits ")
print(long_num)

可是按照他这个说法,最后long_num实际上也是打印不出来的啊…奇怪
那,如果按照他的这个理解说,最后不把long_num都打印出来的话,我的代码可以这么写

#  create variables: int_num, long_num
# int_num and get user input string of only digits
int_num = input("Enter a digit: ")
# create long_num and initialize it as an empty string
long_num = ""
# Create a while loop that runs as long as the input is all digits
while int_num.isdigit() == True:
    long_num = long_num + int_num
    int_num = input("Enter a digit: ")

# finish the loop, print the long_num
print(long_num)

你可能感兴趣的:(Pyhon学习笔记)