1. 程式人生 > >Python第五章課後作業

Python第五章課後作業

5-1條件測試:

car = 'a'
print("Is car == 'a'? I predict True.")
print(car == 'a')
print("\nIs car == 'b'? I predict False.")
print(car == 'b')
car = 'c'
print("Is car == 'c'? I predict True.")
print(car == 'c')
print("\nIs car == 'd'? I predict False.")
print(car == 'd')
car = 'e'
print("Is car == 'e'? I predict True.")
print(car == 'e')
print("\nIs car == 'f'? I predict False.")
print(car == 'f')
car = 'g'
print("Is car == 'g'? I predict True.")
print(car == 'g')
print("\nIs car == 'h'? I predict False.")
print(car == 'h')
car = 'i'
print("Is car == 'i'? I predict True.")
print(car == 'i')
print("\nIs car == 'j'? I predict False.")
print(car == 'j')

執行結果:


5-2更多的條件測試:

print('string')
str1='aaa'
str2='bbb'
print(str1==str2)

print('lower')
print('HHH'.lower()=='hhh')

num1=1
num2=2
print(num1==num2,num1!=num2,num1>num2,num1<num2,num1>=num2,num1<=num2)
print(num1==num2 and num1!=num2)
print(num1==num2 or num1!=num2)

arr=[1,2,3,4]
print(1 in arr)
print(1 not in arr)

執行結果:


5-3外星人顏色1:

alien_color='red'
if alien_color=='red':
	print('You get 5 points')

執行結果:


5-4外星人顏色2:

alien_color='green'
if alien_color=='green':
	print('You get 5 points')
else:
	print('You get 10 points')

執行結果:


5-5外星人顏色3:

alien_color='red'
if alien_color=='green':
	print('You get 5 points')
elif alien_color=='yellow':
	print('You get 10 points')
elif alien_color=='red':
	print('You get 15 points')

執行結果:


5-6人生的不同階段:

age=17
if age<2:
	print('Baby')
elif age>=2 and age<4:
	print('Learn to walk')
elif age>=4 and age <13:
	print('Child')
elif age>=13 and age<20:
	print('Teenager')
elif age>=20 and age<65:
	print('Adult')
else:
	print('Old man')

執行結果:


5-7喜歡的水果:

favorite_fruits=['apple','banana','watermelon']
tmp='apple'
if(tmp in favorite_fruits):
	print("You really like "+tmp)
tmp='banana'
if(tmp in favorite_fruits):
	print("You really like "+tmp)
tmp='watermelon'
if(tmp in favorite_fruits):
	print("You really like "+tmp)
tmp='orange'
if(tmp in favorite_fruits):
	print("You really like "+tmp)
tmp='grapes'
if(tmp in favorite_fruits):
	print("You really like "+tmp)

執行結果:


5-8以特殊方式跟管理員打招呼:

arr=['admin','b','c','d','e']
for name in arr:
	if name == 'admin':
		print("Hello admin, would you like to see a status report?")
	else:
		print("Hello "+name+", thank you for logging in again")

執行結果:


5-9處理沒有使用者的情況:

if not arr:		#如果列表為空
	print('We need to find some users!')
arr.clear()
if not arr:
	print('We need to find some users!')

執行結果:


5-10檢查使用者名稱:

current_user=['A','b','c','d','e']
new_users=['a','c','f','g','h']
unew_users=[cusr.upper() for cusr in current_user]
for user in new_users:
if user.upper() in unew_users:
print(user,'exists,you need to input again')
else:
print(user,"hasn't been used")

執行結果:


5-11序數:

arr=list(range(1,10))
for num in arr:
	print(num,end=' ')
print()
for num in arr:
	if num==1:
		print(str(num)+'st')
	elif num==2:
		print(str(num)+'nd')
	else:
		print(str(num)+'th')

執行結果:


5-12,5-13:略