《python编程从入门到实践》用户输入和while循环

  • input()

  input向用户显示提示,接受用户输入,像是把C中的printf和scanf结合了起来,不用像C那样提示还得单独写一行

1 age = input("how old are you?")
  • int()

  将用户输入转换为数值

1 age = input("how old are you?")
2 age = int(age)#将数字的字符型转变为数值
3 if age > 18:
4     print("adult")
5 输入 19
6 输出为:adult
  • while循环

  while循环不断运行,直到不满足指定条件,而for循环是让每个元素执行一次代码块

  while可以根据用户的输入来确定何时退出循环,和c一样有使用break和continue来退出

1 prompt = "\nplease enter the name of a city you have visited:"
2 prompt += "\n(enter 'quit' when you are finished.)"
3 while 1:
4     city = input(prompt)
5     if city == 'quit':
6         break#退出循环
7     else:
8         print("i'd love to go to "+city)

猜你喜欢

转载自www.cnblogs.com/xzzheng/p/10296737.html
今日推荐