我正在寻找用于在输入函数中打印文本和保存的int的语法。我正在编写一个程序,使用动态术语询问用户的数学问题,我希望能够在同一行上打印这些和一些文本。
我已经尝试过这段代码,希望参数可以表示为print语句:
answer = int(input(oneTerm, '+', twoTerm, '='))
我也试过使用这样的两行:
print(oneTerm, '+', twoTerm, '=')
answer = int(input(''))
但问题是输入是在print语句下面的行上接受的,但我需要它在同一行。
非常感谢任何帮助!
答案 0 :(得分:1)
input()
函数只接受一个字符串参数(而不是多个,如print()
)。使用字符串格式:
answer = int(input('{} + {} = '.format(oneTerm, twoTerm)))
{}
占位符替换为.format()
的两个参数,创建基本相同的字符串以提示用户输入。
有关详细信息,请参阅str.format()
method文档。
答案 1 :(得分:0)
而不是这些方法只需尝试使用:
answer = input(oneTerm, '+', twoTerm, '=')
answer = int(answer)
答案 2 :(得分:0)
这是一个非常古老的问题,但我想最好的解决方案是使用 F-strings 进行更新。它于 2016 年 12 月在 Python >=3.6 中发布(请参阅 PEP 498)。
在一行中:
import React, {useState, useRef} from 'react'
import ReactDOM from 'react-dom'
import Modal from './ModalWrapper'
import {Button, Modal as AntdModal} from 'antd'
const App = () => {
const [on, setOn] = useState(false)
const toggle = () => setOn(!on)
const modalRef = useRef()
return (
<div>
<Button type="warning" onClick={() => setOn(true)}>
Normal Import
</Button>
<br />
<br />
<Button type="primary" onClick={() => modalRef.current.toggleModal()}>
From Modal Component
</Button>
<AntdModal visible={on} onOk={toggle} onCancel={toggle}>
<p>I was imported directly...</p>
<p>I was imported directly...</p>
<p>I was imported directly...</p>
</AntdModal>
<Modal
title="Simple"
ref={modalRef}
onOK={() => alert('Things are now OK :)')}
>
<p>I was imported from Modal Component...</p>
<p>I was imported from Modal Component...</p>
<p>I was imported from Modal Component...</p>
</Modal>
</div>
)
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
我想这是更新的方式,也是最易读的。你们如何看待 F 弦的可读性?很不错吧?