在while循环中打印用户输入的数值 [英] Print out user-input numerical values within a while loop

查看:105
本文介绍了在while循环中打印用户输入的数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手。我正在尝试编写一个while循环,它接收用户输入的数值数据。当用户输入完成时,循环中断。我想找出一种方法来存储和打印用户的所有有效数值数据。



我尝试了什么: < br $> b $ b

I am new to programming. I am trying to write a while loop that takes in user-inputted numerical data. The loop breaks when the user input "done". I am trying to figure out a way to store and print all the valid numerical data of the user.

What I have tried:

values = []
while True:
    user_input = input('Please type in a numerical value')
    if user_input == 'done':
        print('All Done')
        break
    try:
        val_input = float(user_input)
    except ValueError:
        print('You have typed in an invalid value. Please type in a numerical whole number')
        continue
    values.append(user_input)
print(val_input)

推荐答案

您正在将user_input转换为浮点数,但是您希望用户输入整数。使用int类型可能是更好的选择。其次,您将user_input值附加到列表中,而不是转换后的数字。最后,您打印的是最后一次转换的value_input,而不是值列表中的项目。
You are converting user_input to a floating point number, but you want the user to enter a whole number. Using int type may be a better choice. Secondly, you are appending the user_input value to your list, rather than the converted number. And lastly, you are printing the last converted value_input, instead of the items in your values list.


这篇关于在while循环中打印用户输入的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆