本人CSDN博客专栏:https://blog.csdn.net/yty_7
Github地址:https://github.com/yot777/Python-Primary-Learning
6.1 条件判断——if语句
Python的条件判断语句结构是if – elif – else
if condition_1: #如果condition_1为 True 将执行block_1语句
block_1 #如果condition_1为False,将判断condition_2
elif condition_2: #如果condition_2为 True 将执行block_2语句
block_2
else: #如果condition_2为False,将执行block_3语句
block_3
注意:
1、每个条件后面要使用冒号(:),表示接下来是满足条件后要执行的语句块。
2、使用缩进来划分语句块,相同缩进数的语句在一起组成一个语句块。
3、在Python中没有switch – case语句。
Python条件判断——if语句举例(包含输入输出命令的演示):
dog_age = int(input('Age of the dog: '))
human_age=0
if dog_age == 1:
print('This dog is about 14 human years old.')
elif dog_age == 2:
print('This dog is about 22 human years old.')
elif dog_age > 2:
human_age = 22 + (dog_age -2)*5
print('This dog is about '+str(human_age)+' human years old.')
else:
print('Input Error!')
输入:1
输出:This dog is about 14 human years old.
输入:2
输出:This dog is about 22 human years old.
输入:5
输出:This dog is about 37 human years old.
输入:-5
输出: Input Error!
Java条件判断——if语句举例(包含输入输出命令的演示):
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Age of the dog: ");
int dog_age = sc.nextInt();
if(dog_age == 1){
System.out.println("This dog is about 14 human years old.");
}else if(dog_age == 2){
System.out.println("This dog is about 22 human years old.");
}else if(dog_age > 2){
int human_age = 22 + (dog_age -2)*5;
System.out.println("This dog is about "+human_age+" human years old.");
}else{
System.out.println("Input Error!");
}
sc.close();
}
}
输入:1
输出:This dog is about 14 human years old.
输入:2
输出:This dog is about 22 human years old.
输入:5
输出:This dog is about 37 human years old.
输入:-5
输出: Input Error!
参考教程:
廖雪峰的Python教程
https://www.liaoxuefeng.com/wiki/1016959663602400
廖雪峰的Java教程
https://www.liaoxuefeng.com/wiki/1252599548343744
Python3 教程 | 菜鸟教程
https://www.runoob.com/python3/
如果您觉得本篇本章对您有所帮助,欢迎关注、评论、点赞!Github欢迎您的Follow、Star!