
我有一个小秘密,科科
写程序的时候总有报错:“TypeError: cannot concatenate ‘str’ and ‘float’ objects”。因为这个Python2呀比较轴,它认为“+”的意义要么就是加减乘除里的加号,要么就是相同变量的连接。所以,
number=raw_input(number)
print("number="+number)
这样的语句看起来对于java,c什么的逻辑是非常正常,但是对于Python2就不对了,number是个数字(可能是int或者float)你怎么能和字符串连在一起呢?解决方法就是数据类型转换啦。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
f = raw_input("Please input the degrees fahrenheit")
t = (float(f) - 32.0 ) / 1.8
print("The degrees celsius is " + str(t))
C:\Users\Administrator\Desktop>py 3.1.py Please input the degrees fahrenheit: 35.6 The degrees celsius is 2.0
Write a function called maximum(x,y) that returns the biggest of the two parameters x and y.
Test this function with a call like maximum("hej","ha"). What's the result?
问题想当简单,不过题目有点歧义,是两个数字的比较?还是字符串的比较?不过还是有点收获
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def maximum1(x,y): #字符串比较
if(cmp(x,y)): #或者也可以直接比较x>y
return str(y)
else:
return str(x)
def maximum2(x,y): #数字比较
if(int(x)>int(y)):
return str(x)
else:
return str(y)
x=raw_input("Input the first number: ")
y=raw_input("Input the sencond number: ")
print("The biggest parameter is "+ maximum1(x,y))
print("The biggest parameter is "+ maximum2(x,y)) #这个如果输入的是字符串,会报错
C:\Users\Administrator\Desktop>py 4.1.py Input the first parameter: hej Input the second parameter: ha The biggest number is ha
但是如果用maximum1输出两个数字:
C:\Users\Administrator\Desktop>py 4.1.py Input the first parameter: 473 Input the second parameter: 72 The biggest parameter is 72
不要问我为什么,因为字典排序呀~
如果用muximum2输出这两个数字,结果就不一样了
The biggest number is 473
在python中,数组的实现,是用list的,可以在网上轻松的找到各种list的操作方法。就不说啦。
Write a function printlarge(v) that will print out all the elements within the array v, which is larger than 1 000 000.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
num=1
v=list()
while(num!="0"):
num=raw_input("input the number in array(input 0 if you want to finish)")
v.append(num)
print("output of the array: ")
print(v)
C:\Users\Administrator\Desktop>py 6.1.py input the number in array(input 0 if you want to finish)1000000 input the number in array(input 0 if you want to finish)1000000 input the number in array(input 0 if you want to finish)2000000 input the number in array(input 0 if you want to finish)0 output of the array: ['1000000', '1000000', '2000000', '0']
这些都是非常简单的操作,写起来还挺麻烦的,不过以后忘了再回忆起来肯定有帮助的吧~去医务室看了脚,绑了很可爱的绷带,然后!明天要见老师!!!
未来程序员,一般好看,热爱新事物。