Here is the directions for what I need to do:
You are to write a complete program that obtains three pieces of data and then process them. The three pieces of informatio
I like to add a bit of logic to ensure proper values when I do input. My standard way is like this:
import ast
def GetInput(user_message, var_type = str):
while 1:
# ask the user for an input
str_input = input(user_message + ": ")
# you dont need to cast a string!
if var_type == str:
return str_input
else:
input_type = type(ast.literal_eval(str_input))
if var_type == input_type:
return ast.literal_eval(str_input)
else:
print("Invalid type! Try again!")
Then in your main you can do something like this!
def main():
my_bool = False
my_str = ""
my_num = 0
my_bool = GetInput("Give me a Boolean", type(my_bool))
my_str = GetInput("Give me a String", type(my_str))
my_num = GetInput("Give me a Integer", type(my_num))
if my_bool:
print('"{}"'.format(my_str))
print(my_str)
else:
print(my_num * 2)
On stackoverflow, we're here to help people solve problems, not to do your homework, as your question very likely sounds… That said, here is what you want:
def main():
Boolean = input("Give me a Boolean: ")
String = input("Give me a string: ")
Number = int(input("Give me a number: "))
if Boolean == "True":
print('"{s}"\n{s}'.format(s=String))
try:
print('{}\n{}'.format(int(Number)))
except ValueError as err:
print('Error you did not give a number: {}'.format(err))
if __name__ == "__main__":
main()
A few explanations:
Boolean is "True"
checks whether the contained string is actually the word True
, and returns True
, False
otherwise.print(''.format())
builds the double string (separated by \n
) using the string format.Integer
into an int
using int(Integer)
, it will raise a ValueError
exception that gets caught to display a nice message on error.the if __name__ == "__main__":
part is to enable your code to be only executed when ran as a script, not when imported as a library. That's the pythonic way of defining the program's entry point.