阻止输入在Python 3中被打印出来

huangapple go评论101阅读模式
英文:

Prevent Input from Being Printed in Python 3

问题

  1. 我想知道是否可以阻止Python 3中的输入被打印。
  2. 在上面的代码中,例如,如果我输入“236”,控制台会打印:
  3. 236
  4. Even
  5. 我希望输出只是:
  6. Even
  7. 谢谢!
  8. 我听说在Python 2.x中使用raw_input()函数可以实现这个。
英文:

I would like to know if it is possible to prevent an input from being printed in Python 3.

  1. x = int(input())
  2. def func(n):
  3. if n%2==0:
  4. print("Even")
  5. else:
  6. print("Odd")
  7. func(x)

In the code above, for instance, if I input "236", the console prints:

  1. 236
  2. Even

I would like the output to be just:

  1. Even

Thanks!

I've heard this was possible in Python 2.x with the raw_input() function.

答案1

得分: 4

如果您键入输入,它将在Python看到之前通过终端显示在屏幕上。

要抑制这一点,请使用getpass,通常用于密码输入:

  1. from getpass import getpass
  2. x = int(getpass(prompt=''))

请注意,您仍然会看到换行符被打印,导致空行。

英文:

If you type an input, it's being displayed on screen by your terminal before Python even sees it.

To suppress this, use getpass, which is normally used for password input:

  1. from getpass import getpass
  2. x = int(getpass(prompt=''))

Note that you still see the newline being printed, resulting in an empty line.

huangapple
  • 本文由 发表于 2023年6月1日 01:58:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定