python 有效的代码,第二部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 有效的代码,第二部分相关的知识,希望对你有一定的参考价值。

# Today we will learn about if-elif-else clauses and getting input.
# The programming language we've been using all along is Python 3, by the way
# Here's the code:

favorite_number = int(input("What's your favorite number? "))
if favorite_number > 900:
    print("Woah, you like big numbers.")
elif favorite_number == 0:
    print("Zero. The number of emptiness.")
elif favorite_number > 0 and favorite_number < 10:
    print("You like digits, eh?")
elif favorite_number == 42:
    print("The meaning of life!")
else:
    print("You have bad taste.")
    
# and now with explanations:

# Here I added some extra newlines to give us more space to write comments
# Don't worry, blank lines don't do anything in this case.
favorite_number = int(  # This converts the input to an integer*
    input("What's your favorite number? ")  # this gets text input from the user on the console
)
if favorite_number > 900:  # In this case, the operator is ">".
    print("Woah, you like big numbers.")  # As expected, this code executes if the input is greater than 900.
elif favorite_number == 0: # elif is a short form of "else if". Executes if the if condition (and previous elif conditions) 
                           # are all false and the current condition is true
                           # We use "==" instead of "=" for comparsion. This is less ambiguous and also tradition.
    print("Zero. The number of emptiness.")
elif favorite_number > 0 and favorite_number < 10:  # and is an operator that evaluates to True if both inputs are True, otherwise False
    print("You like digits, eh?")
elif favorite_number == 42:  # anot
    print("The meaning of life!")
else:  # else executes if all if and elif statements evaluate to False.
    print("You have bad taste.")  # this is just a silly insult
    
# *and if it isn't an integer, like the user enters "dogs", it'll throw an Exception (an error to you guys!)
# Exceptions can be handled to let the code move on, say ask the user again. But that's for another chapter!
# In this case, it'll throw "ValueError: invalid literal for int() with base 10: 'dog'"

# and by the way, us programmers are very fun and casual. If you asked any other average programmer for some
# sample code they'd fill it with jokes and puns too! For example, a easter egg hidden in the android platform:
# http://stackoverflow.com/questions/13375357/proper-use-cases-for-android-usermanager-isuseragoat

以上是关于python 有效的代码,第二部分的主要内容,如果未能解决你的问题,请参考以下文章

Python 入门学习第二部分:

python:第二部分:面向对象:面向对象object orinted

在 Python3 中使用 smtplib 发送多部分电子邮件,但未显示第二部分

python第二部分

第二部分:异步编程初探与reactor模式

python 类学习 第二部分