- 函数input()暂停程序运行,等待用户输入文本后,赋值给变量以便使用。
- input()接受一个参数是——向用户的提示或说明。
- sublime text等解释器不能运行提示用户输入的互动性程序,需要在终端运行。
- 使用input()时,Python将用户输入解读为字符串。如果只是打印输入,没有问题;但进行数值运算会导致错误。
- 可使用int()函数将字符串类转化为数值类型。
C里面的强制类型转换,不知道在里面是否也是一种函数。eg:a = int(str)#7-1 汽车租赁 car = input("which car would you want?: ") print(f"\nLet me see if I can find you a {car.title()}.\n ") #7-2 餐馆订位 nums = input("\nHow many people are eating?: ") if int(nums) > 10 == 0: print("\nNo sets.\n ") else: print("\nThere're some sets.\n ") #7-3 10的整数倍 num = input("\nEnter a number, and I will tell you if it's integer multiple of ten : ") if int(num) % 10 == 0: print("\nIt's integer multiple of ten. ") else: print("\nIt's not integer multiple of ten. ")
1-书上的练习及对应的结果
- 使用while循环时,在有多种事件能使循环结束的情况下,使用标志(flag)判断程序是否处于活动状态。标志很有用,任意一个实践导致标志变为False时,退出while循环;可避免复杂的比较,简化while语句。
- 避免无限循环,务必对每个循环进行测试,确保其按预期结束。确保循环有一个出口或break得以执行的条件。
- sublime text等一些编辑器内嵌了输出窗口,会导致难以结束无限循环,可通过Ctrl+C结束无限循环。
#7-4 披萨配料 ingredient = "" while True: ingredient = input("Enter a ingredient you want add in your pisa. Enter 'quit' exit.: ") if ingredient == 'quit': break print(f"\nWe will add {ingredient}.title() in it. ") #7-5 电影票 age = "" while True: age = input("\nEnter your age: ") if age == 'quit': break elif int(age) > 12: print("\nYou need pay $15. ") elif int(age) > 3: print("\nYou need pay $10. ") else: print("You are free") #7-6 三种出路 #7-4 披萨配料 ingredient = "" active = True while active: ingredient = input("\nEnter a ingredient you want add in your pisa. Enter 'quit' exit. : ") if ingredient == 'quit': active = False print(f"\nWe will add {ingredient}.title() in it. ") #7-5 电影票 age = "" active = True while active: age = input("\nEnter your age: ") if age == 'quit': active = False elif int(age) > 12: print("\nYou need pay $15. ") elif int(age) > 3: print("\nYou need pay $10. ") else: print("You are free") #7-7 无限循环 while True: print("You are best one in the world!") #Ctrl+C退出
2-书上的练习及对应的结果
在写的过程出现一个错误:inconsistent use of tabs and spaces in inde。