简体   繁体   English

允许用户选择输入

[英]Allowing user to choose an input

I am trying to sharpen my python programming skills by coding solutions to basic physics problems. 我正在尝试通过对基本物理问题的解决方案进行编码来提高我的python编程技能。

The problem states that a spaceship is traveling a distance x at a velocity v towards a destination from Earth. 该问题指出,太空飞船正在以速度v从地球向目的地移动距离x。 I am to find the time elapsed by a stationary observer on Earth and the time elapsed by a passenger aboard the spaceship. 我要找到一个固定的地球观察者所经过的时间,以及太空飞船上一个乘客所经过的时间。 Rather than assigning values to x and v, I am to allow the user to input values for x and v. But, I would like to allow the user to choose how they would like to input their data. 我不是允许将值分配给x和v,而是允许用户输入x和v的值。但是,我希望允许用户选择他们想要输入数据的方式。 For example, the user could put v = some number in meters/sec or the user could put v = a*c where 0 ≤ a ≤ 1 and c = speed of light; 例如,用户可以输入v =以米/秒为单位的某个数字,或者用户可以输入v = a * c,其中0≤a≤1且c =光速; I would like to let the user decide which input is preferred. 我想让用户决定首选哪个输入。

I understand how to ask the user to input a value. 我了解如何要求用户输入值。 ex: x = float(input("What distance has the spaceship traveled: ")) 例如:x = float(input(“太空飞船已经走了多少距离:”))

But how can I let the user decide which v they would like to input? 但是,如何让用户决定他们要输入哪个v?

Possiblility 1 : Two questions 可能性1:两个问题

input(...) returns a string. input(...)返回一个字符串。 Therefore you can ask the user which input style is preferred, à la 因此,您可以询问用户首选哪种输入样式,

Which input format is preferred? ([a]bsolute/[f]raction of c) >

Then use an if / else block to test whether the user has entered a or f . 然后使用if / else块测试用户是否输入af

Subsequently, ask another question 随后,问另一个问题

Enter the desired speed (number) >

and convert the input to float just like you have done above ( float(input(...)) ) 并像上面所做的那样将输入转换为float( float(input(...))

Possibility 2 可能性2

You can ask a question like 你可以问一个问题

Enter spaceship speed:

and test if the last character which is entered by the user is a c . 并测试用户输入的最后一个字符是否为c Then you use the number as fraction of light speed. 然后,将数字用作光速的分数。 Else, you use the number as absolute speed. 否则,您将数字用作绝对速度。

To get the last character of a string, use 要获取字符串的最后一个字符,请使用

s = 'abc'
lastcharacter = s[-1]

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

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