[英]Collect user inputs and then print those to screen in a formatted string
我從用戶那里收集了 3 個輸入,兩個數字a
和b
以及一個數學運算符sign
。 我的代碼如下:
a = int(input('Type the number: '))
b = int(input('Type the number: '))
sign = input('Type a sign as + etc : ')
print(a sign b)
如果輸入是a = 2
, b = 5
, sign = '+'
,我必須使用這些輸入打印到屏幕2 + 5
。
我將如何 go 評估這些對 output 7
的輸入?
您將必須使用if
的序列,或者您可以使用在內置運算符中查找運算operator
的字典(這包含作為可調用函數的標准運算符): https://docs.python.org/3/library/操作員.html
例如,
import operator
operators = {'<': operator.le, '+': operator.add, ...}
print(operators[sign](a, b))
雖然我不太確定這個問題在問什么,
您可以使用加號來連接字符串
a = int(input('Type the number: '))
b = int(input('Type the number: '))
sign = input('Type a sign as + etc : ')
print(str(a) + sign + str(b))
您還可以添加逗號以在字符串之間放置空格。
a = int(input('Type the number: '))
b = int(input('Type the number: '))
sign = input('Type a sign as + etc : ')
print(str(a), sign, str(b))
或使用f 字符串
a = int(input('Type the number: '))
b = int(input('Type the number: '))
sign = input('Type a sign as + etc : ')
print(f"{str(a)} {sign} {str(b)}")
print function 不能同時顯示 int 和 string。
這會成功的
a = int(input('Type the number: '))
b = int(input('Type the number: '))
sign = input('Type a sign as + etc : ')
print(f'{a} {sign} {b}') # f string
f 字符串是較新的格式化語法。
a = int(input('Type the number: '))
b = int(input('Type the number: '))
sign = input('Type a sign as + etc : ')
if sign == "+": print(a + b)
elif sign == "-": print(a - b)
elif sign == "/": print(a / b)
elif sign == "*": print(a * b)
else: print("I can't understand it :(")
您應該定義一個 function。 我想它應該可以解決問題。 a = int(input("Type the number: ")) b = int(input("Type another number: ")) c = input("Please enter a sign as + etc: ")
def sign(x, y):
if c == "+":
return x + y
elif c == "-":
return x - y
elif c == "*":
return x * y
elif c == "/":
return x // y
print(sign(a, b))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.