python怎么将字符串变成int,如何在Python中将字符串转换为int?
我的小示例应用程序的输出如下:
Welcome to the Calculator!
Please choose what you'd like to do:
0: Addition
1: Subtraction
2: Multiplication
3: Division
4: Quit Application
0
Enter your first number: 1
Enter your second number: 1
Your result is:
11
这是因为addition()方法将input()作为字符串而不是数字。如何将它们用作数字?
这是我的整个剧本:
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
keepProgramRunning = True
print"Welcome to the Calculator!"
while keepProgramRunning:
print"Please choose what you'd like to do:"
print"0: Addition"
print"1: Subtraction"
print"2: Multiplication"
print"3: Division"
print"4: Quit Application"
#Capture the menu choice.
choice = raw_input()
if choice =="0":
numberA = raw_input("Enter your first number:")
numberB = raw_input("Enter your second number:")
print"Your result is:"
print addition(numberA, numberB)
elif choice =="1":
numberA = raw_input("Enter your first number:")
numberB = raw_input("Enter your second number:")
print"Your result is:"
print subtraction(numberA, numberB)
elif choice =="2":
numberA = raw_input("Enter your first number:")
numberB = raw_input("Enter your second number:")
print"Your result is:"
print multiplication(numberA, numberB)
elif choice =="3":
numberA = raw_input("Enter your first number:")
numberB = raw_input("Enter your second number:")
print"Your result is:"
print division(numberA, numberB)
elif choice =="4":
print"Bye!"
keepProgramRunning = False
else:
print"Please choose a valid option."
print"
"
我已经说过系统发布了两次问题,检查发布时间。不是我的错,我也不能删除这个问题。
你没有close链接吗?
但这并不能立即解决问题。
python的可能副本-将字符串解析为float或int
因为您编写的计算器可能也接受浮动(1.5, 0.03),所以更健壮的方法是使用这个简单的助手函数:
def convertStr(s):
"""Convert string to either int or float."""
try:
ret = int(s)
except ValueError:
#Try float.
ret = float(s)
return ret
这样,如果int转换不起作用,您将得到一个float返回。
编辑:如果您不完全了解python 2.x如何处理整数除法,那么您的division函数也可能导致一些悲伤的面孔。
简而言之,如果你想让10/2等于2.5而不是2,你就需要做from __future__ import division,或者让其中一个或两个论点浮动,就像这样:
def division(a, b):
return float(a) / float(b)
嘿,这很干净,谢谢!
convertStr = float的工作原理几乎相同。
>>> a ="123"
>>> int(a)
123
以下是一些免费代码:
def getTwoNumbers():
numberA = raw_input("Enter your first number:")
numberB = raw_input("Enter your second number:")
return int(numberA), int(numberB)
更多内置函数:docs.python.org/library/functions.html
从主函数调用子函数时,可以将变量转换为int,然后调用。请参考以下代码:
import sys
print("Welcome to Calculator
")
print("Please find the options:
" +"1. Addition
" +"2. Subtraction
" +
"3. Multiplication
" +"4. Division
" +"5. Exponential
" +"6. Quit
")
def calculator():
choice = input("Enter choice
")
if int(choice) == 1:
a = input("Enter first number
")
b = input("Enter second number
")
add(int(a), int(b))
if int(choice) == 2:
a = input("Enter first number
")
b = input("Enter second number
")
diff(int(a), int(b))
if int(choice) == 3:
a = input("Enter first number
")
b = input("Enter second number
")
mult(int(a), int(b))
if int(choice) == 4:
a = input("Enter first number
")
b = input("Enter second number
")
div(float(a), float(b))
if int(choice) == 5:
a = input("Enter the base number
")
b = input("Enter the exponential
")
exp(int(a), int(b))
if int(choice) == 6:
print("Bye")
sys.exit(0)
def add(a, b):
c = a+b
print("Sum of {} and {} is {}".format(a, b, c))
def diff(a,b):
c = a-b
print("Difference between {} and {} is {}".format(a, b, c))
def mult(a, b):
c = a*b
print("The Product of {} and {} is {}".format(a, b, c))
def div(a, b):
c = a/b
print("The Quotient of {} and {} is {}".format(a, b, c))
def exp(a, b):
c = a**b
print("The result of {} to the power of {} is {}".format(a, b, c))
calculator()
我在这里做的是在将输入的参数转换为int时调用每个函数,希望这有帮助。
在您的情况下,可以这样更改:
if choice =="0":
numberA = raw_input("Enter your first number:")
numberB = raw_input("Enter your second number:")
print"Your result is:"
print addition(int(numberA), int(numberB))
添加DEF(A、B):返回A+B
定义减法(a,b):返回-B
DEF倍增(A、B):返回A*B
DEF部门(A、B):返回A/B
keepProgramrunning=真
打印"欢迎使用计算器!"
保持编程运行时:打印"请选择要执行的操作:"
print"0: Addition"
print"1: Subtraction"
print"2: Multiplication"
print"3: Division"
print"4: Quit Application"
#Capture the menu choice.
choice = raw_input()
if choice =="0":
numberA = input("Enter your first number:")
numberB = input("Enter your second number:")
print"Your result is:" + str(addition(numberA, numberB)) +"
"
elif choice =="1":
numberA = input("Enter your first number:")
numberB = input("Enter your second number:")
print"Your result is:" + str(subtraction(numberA, numberB)) +"
"
elif choice =="2":
numberA = input("Enter your first number:")
numberB = input("Enter your second number:")
print"Your result is:" + str(multiplication(numberA, numberB)) +"
"
elif choice =="3":
numberA = input("Enter your first number:")
numberB = input("Enter your second number:")
print"Your result is:" + str(division(numberA, numberB)) +"
"
elif choice =="4":
print"Bye!"
keepProgramRunning = False
else:
print"Please choose a valid option."
print"
"
解释一下怎么样?
容易的!
if option == str(1):
numberA = int(raw_input("enter first number."))
numberB= int(raw_input("enter second number."))
print""
print addition(numberA, numberB)
etc etc etc
也许下面,那么您的计算器就可以使用任意的基数(例如十六进制、二进制、基数7!)等):(未测试)
def convert(str):
try:
base = 10 # default
if ':' in str:
sstr = str.split(':')
base, str = int(sstr[0]), sstr[1]
val = int(str, base)
except ValueError:
val = None
return val
val = convert(raw_input("Enter value:"))
# 10 : Decimal
# 16:a : Hex, 10
# 2:1010 : Binary, 10
def addition(a, b): return a + b
def subtraction(a, b): return a - b
def multiplication(a, b): return a * b
def division(a, b): return a / b
keepProgramRunning = True
print"Welcome to the Calculator!"
while keepProgramRunning:
print"Please choose what you'd like to do:"
python怎么将字符串变成int,如何在Python中将字符串转换为int?相关推荐
- 如何在Java中将String转换为int?
如何在Java中将String转换为int ? 我的字符串仅包含数字,我想返回它代表的数字. 例如,给定字符串"1234" ,结果应为数字1234 . #1楼 好吧,要考虑的一个非 ...
- 如何在Java中将String转换为int
在本教程中,我们将看到将Java中的String转换为int(或Integer)的各种方法. 您可以使用以下任何一种方式: –使用Integer.parseInt(string) –使用Integer ...
- 如何在Java中将double转换为int?
在本文中,我们将看到如何将double转换为int. 在Java编程中,您将有一个double原语值(例如82.14),但是要执行进一步的操作,您需要一个int值(例如82),所以让我们看看如何在Ja ...
- java中long如何使用_如何在Java中将long转换为int?
问题 如何在Java中将long转换为int? #1 热门回答(218 赞) 简单类型转换应该这样做: long l = 100000; int i = (int) l; 但请注意,大数(通常大于21 ...
- linux shell转换成时间,如何在Bash中将时间戳转换为日期?
如何在Bash中将时间戳转换为日期? 我需要一个将Unix时间戳转换为日期的shell命令或脚本. 输入可以来自第一个参数或来自stdin,允许以下使用模式: ts2date 1267619929 和 ...
- 如何在JavaScript中将十进制转换为十六进制
如何在JavaScript中将十进制值转换为等效的十六进制值? #1楼 如果要将数字转换为RGBA颜色值的十六进制表示形式,我发现这是以下几个技巧中最有用的组合: function toHexStri ...
- 在Java中将boolean转换为int
本文翻译自:Convert boolean to int in Java 在Java中将boolean转换为int的最常用方法是什么? #1楼 参考:https://stackoom.com/ques ...
- scala字符串转int_如何在Scala中将十六进制字符串转换为int?
scala字符串转int The hex string is also known as Hexadecimal Number String is a number created using hex ...
- python 参数个数 同名函数_如何在python中编写不同参数的同名方法
我在Java背景下学习Python(3.x). 我有一个python程序,我在其中创建一个personObject并将其添加到列表中.p = Person("John") list ...
最新文章
- CSS表格中的一些属性
- ubuntu将mysql、nginx添加到环境变量中
- Docker for windows 10
- 浅谈跨平台框架 Flutter 的优势与结构 1
- sysV init服务脚本(入门级)
- 基于itchat实现微信群消息同步机器人
- [CTSC 1999]拯救大兵瑞恩[网络流24题]孤岛营救问题
- 据说微软已撤销了测试部门?
- c语言程序设计大一考题,C语言程序设计期末考试试题(含答案)
- 【观察】SAP HANA+英特尔傲腾:珠联璧合,所向披靡
- 手机淘宝列表页面 的js调用展示
- RocksDB调优指南
- 飘动图片广告html代码,基于JavaScript代码实现随机漂浮图片广告
- AVFoundation照片/视频捕捉功能 小视频/直播
- TortoiseGit拉取gitee代码
- mac android usb共享网络,mac 网络共享软件 手机usb共享网络方法和技巧详解介绍
- 中恒建模助手插件和绿色建筑的完美结合
- 丰田chr内外循环怎么区分_丰田C-HR怎么开启暖风
- [转载]扩展Log4Net中的ILog实现自定义日志字段
- 数据结构绪论——什么是数据结构?