Task 06:FOR、IF以及while


前言

本次主要讲解循环语句,其中包括if语句及其嵌套语句的使用、for语句和while语句。


一、IF语句

people = 20
cats = 30
dogs = 15


if people < cats:
    print("Too many cats! The world is doomed!")

if people > cats:
    print("Not many cats! The world is saved!")

if people < dogs:
    print("The world is drooled on!")     

if people > dogs:
    print("The world is dry!")

dogs += 5

if people >= dogs:
    print("People are greater than or equal to dogs.")

if people <= dogs:
    print("People are less than or equal to dogs.")

if people == dogs:
    print("People are dogs.")

在这里插入图片描述

附加练习

1、你认为 if 对它下面的代码起什么作用?
if 语句在代码中创建了一个“分支”(branch),有点类似于在一本冒险书中,你选择了哪个答案,就翻到对应的那一页,如果你选择了不同的答案,就会去到不同的地方。if 语句就是告诉脚本,如果这个布尔表达式是 True,那就运行它下面的代码,否则的话就跳过。
2、为什么 if 下面的代码要缩进 4 个空格?
通过一行代码结尾的冒号告诉 Python 你在创建一个新的代码块,然后缩进四个空格告诉 Python 这个代码块中都有些什么。这就跟本书前半部分中你学的函数是一样的。
3、如果没有缩进会发生什么?
如果没有缩进,你很可能收到一个错误提示。Python 一般会让你在一个带 : 的代码行下面缩进一些内容。
4、你能把一些布尔表达式放进 if 语句吗?试试看。

if True:
    print("这是True")
if  False:
    print("这是False")
if True and False:
    print("false")
if True or False:
    print("false")

在这里插入图片描述

5、如果你改变 people,cats 和 dogs 的初始值会发生什么?

people = 15
cats = 30
dogs = 20


if people < cats:
    print("Too many cats! The world is doomed!")

if people > cats:
    print("Not many cats! The world is saved!")

if people < dogs:
    print("The world is drooled on!")     

if people > dogs:
    print("The world is dry!")

dogs += 5

if people >= dogs:
    print("People are greater than or equal to dogs.")

if people <= dogs:
    print("People are less than or equal to dogs.")

if people == dogs:
    print("People are dogs.")

在这里插入图片描述

people = 30
cars = 40
trucks = 15


if cars > people:
    print("We should take the cars.")
elif cars < people:
    print("We should not take the cars.")
else:
    print("We can't decide.")

if trucks > cars:
    print("That's too many trucks.")
elif trucks < cars:
    print("Maybe we could take the trucks.")
else:
    print("We still can't decide.")

if people > trucks:
    print("Alright, let's just take the trucks.")
else:
    print("Fine, let's stay home then.")

在这里插入图片描述
附加练习
1、试着猜猜 elif 和 else 的作用是什么?
else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子句则是需要检查更多条件时会被使用,与if和else一同使用,elif是else if 的简写。
2、改变 cars,people,和 trucks 的数值,然后追溯每一个 if 语句,看看什么会被打印出来。

people = 25
cars = 18
trucks = 30


if cars > people:
    print("We should take the cars.")
elif cars < people:
    print("We should not take the cars.")
else:
    print("We can't decide.")

if trucks > cars:
    print("That's too many trucks.")
elif trucks < cars:
    print("Maybe we could take the trucks.")
else:
    print("We still can't decide.")

if people > trucks:
    print("Alright, let's just take the trucks.")
else:
    print("Fine, let's stay home then.")

在这里插入图片描述
3、试试一些更复杂的布尔表达式,比如cars > people 或者 trucks < cars。

people = 25
cars = 18
trucks = 30


if cars > people or trucks < cars :
    print("We should take the cars.")
    print("Maybe we could take the trucks.")
elif cars < people  and trucks > cars:
    print("We should not take the cars.")
    print("That's too many trucks.")
else:
    print("We can't decide.")
    print("We still can't decide.")    

if people > trucks:
    print("Alright, let's just take the trucks.")
else:
    print("Fine, let's stay home then.")

在这里插入图片描述

常见问题
如果多个 elif 块都是 True 会发生什么? Python 从顶部开始,然后运行第一个是 True 的代码块,也就是说,它只会运行第一个。

1.IF嵌套使用

print("""You enter a dark room with two doors.Do you go through door #1 or door #2?""")

door = input("> ")

if door == "1":
    print("There's a giant bear here eating a cheese cake.")
    print("What do you do?")
    print("1. Take the cake.")
    print("2. Scream at the bear.")     

    bear = input("> ")

    if bear == "1":
        print("The bear eats your face off. Good job!")
    elif bear == "2":
        print("The bear eats your legs off. Good job!")
    else:
        print(f"Well, doing {bear} is probably better.")
        print("Bear runs away.")

elif door == "2":
    print("You stare into the endless abyss at Cthulhu's retina.")
    print("1. Blueberries.")
    print("2. Yellow jacket clothespins.")
    print("3. Understanding revolvers yelling melodies.")

    insanity = input("> ")

    if insanity == "1" or insanity == "2":
        print("Your body survives powered by a mind of jello.")
        print("Good job!")
    else:
        print("The insanity rots your eyes into a pool of muck.")
        print("Good job!")
    
else:
    print("You stumble around and fall on a knife and die. Good job!")

在这里插入图片描述
附加练习
给这个游戏加一些新内容,同时改变用户可以做的决定。尽可能地扩展这个游戏,直到它变得很搞笑。

print("""You enter a dark room with two doors.Do you go through door #1 or door #2 or door #3?""")

door = input("> ")

if door == "1":
    print("There's a giant bear here eating a cheese cake.")
    print("What do you do?")
    print("1. Take the cake.")
    print("2. Scream at the bear.")     

    bear = input("> ")

    if bear == "1":
        print("The bear eats your face off. Good job!")
    elif bear == "2":
        print("The bear eats your legs off. Good job!")
    else:
        print(f"Well, doing {bear} is probably better.")
        print("Bear runs away.")

elif door == "2":
    print("You stare into the endless abyss at Cthulhu's retina.")
    print("1. Blueberries.")
    print("2. Yellow jacket clothespins.")
    print("3. Understanding revolvers yelling melodies.")

    insanity = input("> ")

    if insanity == "1" or insanity == "2":
        print("Your body survives powered by a mind of jello.")
        print("Good job!")
    else:
        print("The insanity rots your eyes into a pool of muck.")
        print("Good job!")
elif door == "3":
    print("What do you want to do?")
    print("1. Watching TV.")
    print("2. eating fruits.")
    print("3. Sleeping.")
    
    insanity = input("> ")

    if insanity == "1" :
        print("It is a good choice.")
        print("Good job!")
    elif  insanity == "2":
        print("It is good for you.")
        print("Good job!")
    else:
        print("You are a good boy.")
else:
    print("You stumble around and fall on a knife and die. Good job!")

在这里插入图片描述
常见问题
1、我能用一系列的 if 语句来代替 elif 吗?
在某些情况下可以,但是取决于每个 if/else 是怎么写的。如果这样的话还意味着 Python 将会检查每一个 if-else 组合,而不是像 if-elif-else 组合那样只会检查第一个是 false 的。
2、如何表示一个数字的区间?
有两种方式:一种是 0 < x < 10 或者 1 <= x < 10 这种传统表示方法,另一种是 x 的区间是 (1, 10)。
3、如果想在 if-elif-else 代码块中放更多的选择怎么办?
为每种可能的选择增加更多的 elif 块。

二、FOR语句

the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
    print(f"This is count {number}")

# same as above
for fruit in fruits:
    print(f"A fruit of type: {fruit}")

# also we can go through mixed lists too
# notice we have to use {} since we don't know what's in it
for i in change:
    print(f"I got {i}")

# we can also build lists, first start with an empty one
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
    print(f"Adding {i} to the list.")
# append is a function that lists understand
    elements.append(i)

# now we can print them out too
for i in elements:
    print(f"Element was: {i}")

在这里插入图片描述
常见问题

1、如何创建一个二维列表?
可以用这种列表中的列表:[[1,2,3],[4,5,6]]
2、列表(lists)和数组(arrays)难道不是一个东西吗?
这取决于语言以及实现方法。在传统术语中,列表和数组的实现方式不同。在 Ruby 中都叫做 arrays,在 python 中都叫做 lists。所以我们就把这些叫做列表。
3、为什么 for-loop 可以用一个没有被定义的变量?
变量在 for-loop 开始的时候就被定义了,它被初始化到了每一次 loop 迭代时的当前元素中。
4、为什么 range(1, 3) 中的 i 只循环了两次而不是三次?
range() 函数只处理从第一个到最后一个数,但不包括最后一个数,所以它在 2 就结束了。这是这类循环的通用做法。
5、element.append() 的作用是什么?
它只是把东西追加到列表的末尾。打开 Python shell 然后创建一个新列表。

三、while语句

现在我们来看一个新的循环: while-loop。只要一个布尔表达式是 True,while-loop 就会一直执行它下面的代码块。
while-loop,它所做的只是像 if 语句一样的测试,但是它不是只运行一次代码块,而是在 while 是对的地方回到顶部再重复,直到表达式为 False。
但是 while-loop 有个问题:有时候它们停不下来。如果你的目的是让程序一直运行直到宇宙的终结,那这样的确很屌。但大多数情况下,你肯定是需要你的循环最终能停下来的。
为了避免这些问题,你得遵守一些规则:
1、保守使用 while-loop,通常用 for-loop 更好一些。
2、检查一下你的 while 语句,确保布尔测试最终会在某个点结果为 False。
3、当遇到问题的时候,把你的 while-loop 开头和结尾的测试变量打印出来,看看它们在做什么。

i = 0
numbers = []

while i < 6:
    print(f"At the top i is {i}")
    numbers.append(i)

    i = i + 1
    print("Numbers now: ", numbers)
    print(f"At the bottom i is {i}")


print("The numbers: ")

for num in numbers:
    print(num)

在这里插入图片描述
常见问题

1、for-loop 和 while-loop 的区别是什么?
for-loop 只能迭代(循环)一些东西的集合,而 while-loop 能够迭代(循环)任何类型的东西。不过,while-loop 很难用对,而你通常能够用 for-loop 完成很多事情。
2、循环好难,应该如何理解它们?
人们不理解循环的主要原因是他们跟不上代码的运行。当一个循环运行的时候,它会过一遍代码块,到结尾之后再跳到顶部。为了直观表现这个过程,你可以用 print 打印出循环的整个过程,把 print 行写在循环的前面、顶部、中间、结尾。研究一下输出的内容,试着理解它是如何运行的。

分支和函数

from sys import exit

def gold_room():
    print("This room is full of gold. How much do you take?")

    choice = input("> ")
    if "0" in choice or "1" in choice:
        how_much = int(choice)
    else:
        dead("Man, learn to type a number.")

    if how_much < 50:
        print("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")


def bear_room():
    print("There is a bear here.")
    print("The bear has a bunch of honey.")
    print("The fat bear is in front of another door.")
    print("How are you going to move the bear?")
    bear_moved = False

    while True:
         choice = input("> ")

         if choice == "take honey":
            dead("The bear looks at you then slaps your face")
         elif choice == "taunt bear" and not bear_moved:
            print("The bear has moved from the door.")
            print("You can go through it now.")
            bear_moved = True
         elif choice == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg.")
         elif choice == "open door" and bear_moved:
            gold_room()
         else:
             print("I got no idea what that means.")


def cthulhu_room():
     print("Here you see the great evil Cthulhu.")
     print("He, it, whatever stares at you and you go insane.")
     print("Do you flee for your life or eat your head?")

     choice = input("> ")

     if "flee" in choice:
        start()
     elif "head" in choice:
         dead("Well that was tasty!")
     else:
          cthulhu_room()


def dead(why):
      print(why, "Good job!")
      exit(0)

def start():
      print("You are in a dark room.")
      print("There is a door to your right and left.")
      print("Which one do you take?")

      choice = input("> ")

      if choice == "left":
            bear_room()
      elif choice == "right":
           cthulhu_room()
      else:
         dead("You stumble around the room until you starve.")


start()

在这里插入图片描述
常见问题

1、为什么你要用 while True?
这样可以构建一个无限循环。
2、exit(0) 是干什么用的?
在很多操作系统中,一个程序可以用 exit(0) 来结束,其中传入的数字代表是否有错误。如果你用 exit(1) 代表有 1 个错误, exit(0) 则代表程序正常退出。它不同于通常的布尔逻辑(0==False),因为你可以用不同的数字来表示不同的错误结果。你可以用 exit(100) 来表示与 exit(2) 或者 exit(1) 不同的错误结果。
3、为什么 input() 有时会被写成 input(’> ')?
input 的参数是一个字符串,所以要在获取用户输入的内容前面加一个提示符。这里 > 也可以换成想要提示用户的文字。

总结

本篇文章主要讲解了for、if、 while这三种常用的循环,并举例来理解其工作原理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Sure, I can help you with that. Here is the solution to your problem using Java: Task 1: Create an ArrayList of strings representing a list of your hobbies. ```java ArrayList<String> hobbies = new ArrayList<String>(); hobbies.add("Reading"); hobbies.add("Swimming"); hobbies.add("Cooking"); hobbies.add("Playing basketball"); ``` Task 2: Read from a file “student_hobbies.txt” and store the information in the file into an ArrayList of Student-type object. You will need to create a Student class for this. ```java import java.util.*; import java.io.*; public class Student { String name; ArrayList<String> hobbies = new ArrayList<String>(); public Student(String name, ArrayList<String> hobbies) { this.name = name; this.hobbies = hobbies; } public String getName() { return name; } public ArrayList<String> getHobbies() { return hobbies; } } public class Main { public static void main(String[] args) throws IOException { File file = new File("student_hobbies.txt"); Scanner sc = new Scanner(file); ArrayList<Student> students = new ArrayList<Student>(); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] parts = line.split(" "); String name = parts[0]; ArrayList<String> hobbies = new ArrayList<String>(); for (int i = 1; i < parts.length; i++) { hobbies.add(parts[i]); } Student student = new Student(name, hobbies); students.add(student); } sc.close(); } } ``` Task 3: Sort the list of students by ascending order of names. ```java Collections.sort(students, new Comparator<Student>() { public int compare(Student s1, Student s2) { return s1.getName().compareTo(s2.getName()); } }); ``` Task 4: For each of your hobby, find out how many students in the student ArrayList share that hobby with you. ```java for (String hobby : hobbies) { int count = 0; for (Student student : students) { if (student.getHobbies().contains(hobby)) { count++; } } System.out.println("Number of students who share the hobby " + hobby + " with you: " + count); } ``` I hope this helps you! Let me know if you have any other questions.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Never give up

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值