In []: int(a) ValueError: invalid literal for int() with base 10: '5.5' In []: float(a) Out[]: 5.5 In []: int(float(a)) Out[]: 5 You can also type cast a number into a string: In []: b = 6 In []: a + b TypeError: cannot concatenate 'str' and 'int' objects In []: a + str(b) Out[]: '5.56' In []: float(a) + b Out[]: 11.5 Explain the difference between as concatenation and as numeric addition. + + The following code picks a random number between 1 and 4 (inclusive, meaning it includes both 1 and 4) and lets the user guess once. In part b below, you will modify the program so that it indicates whether the user guessed too low, too high, or correctly. from __future__ import 1 print_function # must be first in file import random 2 3 def 4 guess_once(): 5 secret = random.randint(1, 4) 6 have a number between 1 and 4.') 7 = int(raw_input('Guess: ')) if 8 guess != secret: 9 print('Wrong, my number is ', secret, '.', sep='') else: 10 11 print('Right, my number is', guess, end='!\n') In []: guess_once() I have a number between 1 and 4 inclusive. 3 Right, my number is 3! In []: guess_once() I have a number between 1 and 4 inclusive. Guess: 3 Wrong, my number is 4. print('Wrong, my number is ', secret, In line 9, '.', sep='') has four arguments: three strings and a keyword=value
In []: int(a) ValueError: invalid literal for int() with base 10: '5.5' In []: float(a) Out[]: 5.5 In []: int(float(a)) Out[]: 5 You can also type cast a number into a string: In []: b = 6 In []: a + b TypeError: cannot concatenate 'str' and 'int' objects In []: a + str(b) Out[]: '5.56' In []: float(a) + b Out[]: 11.5 Explain the difference between + as concatenation and + as numeric addition. The following code picks a random number between 1 and 4 (inclusive, meaning it includes both 1 and 4) and lets the user guess once. In part b below, you will modify the program so that it indicates whether the user guessed too low, too high, or correctly. 1 2 3 4 5 6 7 8 9 10 11 from __future__ import print_function # must be first in file import random def guess_once(): secret = random.randint(1, 4) have a number between 1 and 4.') = int(raw_input('Guess: ')) if guess != secret: print('Wrong, my number is ', secret, '.', sep='') else: print('Right, my number is', guess, end='!\n') In []: guess_once() I have a number between 1 and 4 inclusive. 3 Right, my number is 3! In []: guess_once() I have a number between 1 and 4 inclusive. Guess: 3 Wrong, my number is 4. In line 9, print('Wrong, my number is ', secret, '.', sep='') has four arguments: three strings and a keyword=value
1.3.4.A%20NestedBranchingAndInput.docx