请用户输入一个数学表达式,程序会给出运算结果,
虽然这个程序的功能无比初级,只会算加法减法乘法和除法,还对输入格式进行严格限制,用户稍微一淘气,立马就崩溃的节奏。
但是,莫欺少年穷,我们编程的小宇宙每时每刻都在积聚力量呢。
在这个程序里,我们通过判断用户输入的运算符决定调用哪一种数学运算,即运用条件判断,使得程序运行走向出现分歧,不同条件执行不同代码,进行不同的处理。
第二个程序我们是根据用户年龄判断其生日是不是一个重要的日子。
18岁前的每一年,生日都是重要哒。那时还呆在父母身边,生日前的好几天就开始预报、策划、盼望......
还会借机跟父母要期待已久的礼物。
生日那天会有大餐,会有大大的生日蛋糕,运气好的话也许还会有生日趴体,会收到很多很多祝福,很多很多礼物......
美得鼻涕泡都快出来了!
好吧,我们的程序也会应景地同意:您的生日很重要!
知道为什么有些地方18岁要举行成人礼么?那是因为这之后的许多年你的生日都不再重要了!
23岁那一年的生日重要么?重要啊,因为那是你大学毕业迈入社会直面真实生活的第一年,但谁顾得上啊?找工作很忙好不好,好不容易找到了适应新环境压力很大好不好!
30而立、40不惑生日重要不?你说重要就重要,你说不重要就不重要,本人正在爬坡,没心情回答无聊问题。
终于50知天命啦,爱咋咋地吧!我要庆祝一下我的生日,庆祝五十年前的今天我娘把我带到这个多彩的世界!60大寿要庆祝,66大寿更要大庆的,好吧65岁开始,以后的每个生日都重要吧。
(这只是为了教学在逗乐子,其实我们的每个生日都重要!)
# ---------- IS BIRTHDAY IMPORTANT ----------
# We'll provide different output based on age
# 1 - 18 -> Important
# 21, 50, >65 -> Important
# All others -> Not important
# Receive age and store in age
# eval() converts a string into an integer if it meets the guidelines
age = int(input("Enter age: "))
# Logical operators can be used to combine conditions
# and: If both are true it returns true
# or: If either condition is true then true
# not: Convert a true condition into a false
# If age is both greater than or equal to 1 and less than or equal to 18 Important
if (age >= 1) and (age <= 18):
print("Important Birthday")
# If age is either 21 or 50 Important
elif (age ==21) or (age ==50):
print("Important Birthday")
# We check if age is less than 65 and then convert true to
# false and vice versa
# This is the same as if we put age > 65
elif not(age < 60):
print("Important Birthday")
# Else not important
else:
print("Sorry Not Important")
最后就是根据您的年龄和出生月份判断您是该上幼儿园呢,还是小学、初中、高中或滚去上大学,这个程序可把我累够呛。
不是说到了七岁您就能上小学,得是您到了七岁还得在九月一日以前出生,您当年才能上小学。
究竟是因为这个九月一日才成了开学的日子,还是因为九月一日是开学的日期才有了这个规定呢?
总之判断起来不仅得判断年龄还得判断出生月份,条件嵌套条件,逻辑错误语法错误交相辉映,好不容易才清除掉这些bug调好程序哒。
# ---------- PROBLEM : DETERMINE GRADE ----------
# If age is 5 Go to Kindergarden
# Ages 6 through 17 goes to grades 1 through 12
# If age is greater then 17 say go to college
# Try to complete with 10 or less lines
# Ask for the age
age, birthMonth = input("Enter age and birth month(num): ").split()
age = int(age)
birthMonth = int(birthMonth)
# Handle if kindergarten
if age < 7 or (age==7 and birthMonth>=9):
print("Too Young for School")
# Handle primary school
elif (age < 13) or (age ==13 and birthMonth>=9):
if birthMonth>=9:
grade = age - 7
else:
grade = age - 6
print("Go to {} grade of primary school".format(grade))
# Handle secondary school
elif (age < 16) or (age ==16 and birthMonth>=9):
if birthMonth>=9:
grade = age - 12
else:
grade = age - 11
print("Go to {} grade of secondary school".format(grade))
# Handle high school
elif (age < 19) or (age ==19 and birthMonth>=9):
if birthMonth>=9:
grade = age - 16
else:
grade = age - 15
print("Go to {} grade of high school".format(grade))
# Handle college
else:
print("Now maybe you go to College")
详细视频: