python处理输入和输出

xiaoxiao2021-02-28  124

1.从命令行获取信息 >>> num = input(); 5 >>> num 5 >>> num2 = input(); 5.0 >>> num2 5.0 >>> str1 = input(); heres Traceback (most recent call last):   File "<pyshell#21>", line 1, in <module>     str1 = input();   File "<string>", line 1, in <module> NameError: name 'heres' is not defined >>> str1 = input(); 'heres' >>> str1 'heres' 注:input函数用于收集信息,python将尝试为输入的内容匹配正确的数据类型。如果用户输入是5,那么这个值将保存为整数。如果用户输入时5.0该值将保存为浮点数。显然,如果输入的字符串没有加引号,就会出现输出报错。 >>> str3 = raw_input(); heres >>> str3 'heres' >>> num3 = raw_input() 5 >>> num3 '5' >>> type(num3) <type 'str'> >>>  注:raw_input函数用于收集任何非数字信息。它吧用户输入的任何内容都保存成一个字符串。我们可以将提示作为参数放入函数中,例:raw_input("please give me your age:") 综上所述,使用raw_input比使用input更安全点。

》》》》》以上论述是针对python2.x版本,在python3.x中,只保留了input,且其输出结果都是字符串《《《《《《《《

以下是python3.x的实例:

#testName.py def func1(): print("my name is testName ,func1") # xiaoming_age = int(input("输入年龄:")) xiaoming_age = input("输入年龄:") return xiaoming_age def func2(x): xiaoming_age = 16 if(xiaoming_age==x): return '有' else: return '没有' if __name__ == "__main__": x = func1() print('%s具有类型转换功能'%func2(x))2.转化输入 使用raw_input()函数获得用户的age,接着用float()把age转换成浮点数。 >>> age = raw_input() 90 >>> age '90' >>> age = float(age) >>> age 90.0 >>> age = int(age) >>> age 90 3.格式化输出 3.1 >>> greeting = "good {},{},how are you?" >>> time = 'morning' >>> name = 'heres' >>> print greeting.format(time,name) good morning,heres,how are you? 3.2 >>> line = 'hello,{0},{1}' >>> print line.format('wang','zuan')

hello,wang,zuan

3.3

>>> str = input("输入名字:")输入名字:heres>>> print('我的名字叫%s'%str)我的名字叫heres

转载请注明原文地址: https://www.6miu.com/read-33386.html

最新回复(0)