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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值