7.1 创建多行字符串的方式:
01 prompt="if you tell me who you are, we can personalize the message you see." 02 prompt+="what is your first name? "; 03 04 name=input(prompt); 05 print("\nhello,"+name+‘!‘); >>> if you tell me who you are, we can personalize the message you see.what is your first name? franz ? ? hello,franz! |
7.2 使用函数int()获得整数输入
01 height = input("How tall are you, in inches? ") 02 height = int(height) 03 if height >= 36: 04 print("\nYou‘re tall enough to ride!") 05 else: 06 print("\nYou‘ll be able to ride when you‘re a little older.") >>> How tall are you, in inches? 20 ? ? You‘ll be able to ride when you‘re a little older. |
7.3 求模运算
目的:求模运算符 (%) 是一个很有用的工具, 它将两个数相除并返回余数
01 number = input("Enter a number, and I‘ll tell you if it‘s even or odd: ") 02 number = int(number) 03 if number % 2 == 0: 04 print("\nThe number " + str(number) + " is even.") 05 else: 06 print("\nThe number " + str(number) + " is odd.") >>> Enter a number, and I‘ll tell you if it‘s even or odd: 45 ? ? The number 45 is odd. |
7.4 while 循环:
01 prompt="\nTell me sth,and I will repeat back to you"; 02 prompt+="\nEnter ‘quit‘ to end the program. "; 03 act=True; 04 while act: 05 message=input(prompt); 06 if message==‘quit‘: 07 act=False; 08 else: 09 print(message); >>> Tell me sth,and I will repeat back to you Enter ‘quit‘ to end the program. no no ? ? Tell me sth,and I will repeat back to you Enter ‘quit‘ to end the program. yes yes ? ? Tell me sth,and I will repeat back to you Enter ‘quit‘ to end the program. quit |
01 # Break test & continue tst 02 03 prompt="\nTell me sth,and I will repeat back to you"; 04 prompt+="\nEnter ‘quit‘ to end the program. "; 05 while True: 06 message=input(prompt); 07 if message==‘quit‘: 08 break; 09 else: 10 print(message); 11 12 13 current_number = 0 14 while current_number < 10: 15 current_number += 1 16 if current_number % 2 == 0: 17 continue 18 print(current_number) >>> Tell me sth,and I will repeat back to you Enter ‘quit‘ to end the program. quit 1 3 5 7 9 |
01 # test:remove specific element 02 03 # tip1:remove() 04 pets = [‘dog‘, ‘cat‘, ‘dog‘, ‘goldfish‘, ‘cat‘, ‘rabbit‘, ‘cat‘]; 05 while ‘cat‘ in pets: 06 pets.remove(‘cat‘); 07 print(pets); 08 09 # tip2:del 10 pets = [‘dog‘, ‘cat‘, ‘dog‘, ‘goldfish‘, ‘cat‘, ‘rabbit‘, ‘cat‘]; 11 index=0; 12 while ‘cat‘ in pets: 13 if pets[index]==‘cat‘: 14 del pets[index]; 15 index=index; 16 else: 17 index+=1; 18 print(pets); 19 20 # tip1 is better than tip2 >>> [‘dog‘, ‘dog‘, ‘goldfish‘, ‘rabbit‘] [‘dog‘, ‘dog‘, ‘goldfish‘, ‘rabbit‘] |
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
? ?
原文:https://www.cnblogs.com/lovely-bones/p/10994573.html