简体   繁体   English

Python 标准输入错误,从 pycharm 复制的代码在 CMD 中不起作用

[英]Python stdin errors, copied code from pycharm wont work in CMD

Learning python as a beginner.初学者学习python。 I wanted to copy my code into CMD but it won't work.我想将我的代码复制到 CMD 但它不起作用。 Here is code这是代码

calculation_to_units = 24
name_of_unit = "hours"


def days_to_units(number_of_days):
    if number_of_days > 0:
      return f"{number_of_days} days are {number_of_days * calculation_to_units} {name_of_unit}"
    else:
        return "Liczba dni musi być dodatnia :)"



user_input = input("Hello user, enter amount of days you want to calculate to hours\n")
user_input_number = int(user_input)

calculated_value = days_to_units(user_input_number)
print(calculated_value)

despite the fact that it works in Pycharm. I already checked paths.尽管它在 Pycharm 中有效。我已经检查了路径。 I am not able to solve this problem.我无法解决这个问题。 When I type in python3 test.py it also says C:\Users\Borys\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\Users\Borys\test.py': [Errno 2] No such file or directory当我输入 python3 test.py 时,它还显示 C:\Users\Borys\AppData\Local\Programs\Python\Python310\python.exe: can't open file 'C:\Users\Borys\test.py': [Errno 2] 没有那个文件或目录

Also recieved this message "unable to initialize device prn in python"还收到此消息“无法在 python 中初始化设备 prn”

My inte.net connection is so bad that it took me 10 minutes to sign up on stack overflow.我的 inte.net 连接非常糟糕,以至于我花了 10 分钟才注册了 stack overflow。 Additionaly my english knowledge is too small for complex programming explainations.另外,我的英语知识太少,无法解释复杂的编程。

It can be difficult to paste code that calls input() into a python shell. Both the shell and the input() function read stdin.可能很难将调用input()的代码粘贴到 python shell 中。shell 和input() function 都读取标准输入。 As soon as python reads the line with input() , it calls input() and that consumes the next line on stdin.一旦 python 读取带有input()的行,它就会调用input()并使用标准输入上的下一行。 In your case, that was a python code line intended to set a variable.在您的例子中,那是一个旨在设置变量的 python 代码行。 That line was consumbed by input and was not read or executed by python. So you got a "variable not defined" error.该行已被input消耗,未被 python 读取或执行。因此出现“变量未定义”错误。 But you would also have gotten another error because that line was also not the stuff you wanted to input.但是您也会遇到另一个错误,因为该行也不是您想要输入的内容。

Suppose you had the script假设你有脚本

val = input("Input value: ")
i_val = int(val)
print(i_val)

And pasted it into the python shell并将其粘贴到 python shell

>>> val = input("Input value: ")
Input value: i_val = int(val)
>>> print(i_val)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'i_val' is not defined. Did you mean: 'eval'?

The line i_val = int(val) was assigned to val - it was not interpreted by the shell. There would be an ">>> " if it did.i_val = int(val)被分配给val - 它没有被 shell 解释。如果它解释了,就会有一个“>>>”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM