2.7 base. (1) is here.
Python determines whether all objects will be True or False when treated as a bool value.
object | Authenticity |
---|---|
False、None、0(Integer, floating point, imaginary), Empty string, empty list, empty tuple, empty dictionary | False |
other than that | True |
>>> a = 0
>>> print a == 0
True
>>> print a == True
False
>>> print a == False
True
>>> a = 1
>>> print a == True
True
>>> print a == False
False
if Add a colon to the end of the conditional expression.
>>> a = 0
>>> if a:
print 'TRUE'
else:
print 'FALSE'
FALSE
#Inversion by not
>>> if not a:
print 'TRUE'
else:
print 'FALSE'
TRUE
#Type determination with isinstance
>>> if isinstance(a, int):
print 'Integer'
Integer
#Comparison operators are standard
>>> if a <= 3
print 'Less than 3'
Less than 3
#In or not in to indicate whether it is included in a list or tuple element
>>> list = [0,1,2,3,4]
>>> if 3 in list
print 'found'
found
#Add condition with elif
a = raw_input('input number >')
a = int(a)
if a < 5:
print 'less than 5'
elif a < 10:
print 'less than 10'
else:
print 'greater than or equal to 10'
>>> a = 5
>>> if a > 3 and a < 5:
print 'True'
else
print 'False'
False
while
>>> while a < 3:
... print('sushi')
... a += 1
...
sushi
sushi
sushi
for..in.. Use as an Iterator for lists and tuples.
>>> sushi = ['maguro', 'hamachi', 'engawa']
>>> for s in sushi:
... print s
...
maguro
hamachi
engawa
range The built-in function range () produces a list with arithmetic progressions as elements.
>>> for i in range(3):
... print 'hoge'
...
hoge
hoge
hoge
try:
Processing that may cause an exception
except exception name:
Error handling
else:
What to do when an exception does not occur
finally:
Processing that must pass
a = ['a', 'b', 'c']
number = int(raw_input('input a number > '))
try:
b = a[number]
except IndexError:
print 'index error!(' + str(number) + ')'
else:
print b
finally:
print 'end of program'
#Import module
import time
import random
num_of_times = 5
game_time = 25
num_of_range = 100
start_time = time.time() #Current time
for i in range(num_of_times):
#Create double-digit random addition
a = random.randint(1, num_of_range)
b = random.randint(1, num_of_range)
c = a + b
ans = input(str(a) + '+' + str(b) + '= ' ) #Substitute keyboard input for ans
if ans != c:
print 'wrong answer'
print 'answer is ' + str(c)
break
elif time.time() - start_time > game_time:
print 'timeout'
break
else:
print 'Bingo!'
else:
#Pass here only when exiting the for loop (all correct answers)
print 'Complete!'
print 'end of program'
Recommended Posts