How to make program like this.???
Input : 4
*
* *
* *
* * * *
I would love to know how to do this, it's been bugging me all week but it was only an extra credit question so my teacher never explained how to do it!! :(
http://i.stack.imgur.com/qlyGu.jpg
I thought this would be fun to try, here is my solution:
PROMPT_MSG = "Please enter a whole number, greater than 1"
PROMPT_MSG_ERR = "Oops! Please try again.."
def validate_input(input):
try:
assert int(input) > 1
return int(input)
except (ValueError, AssertionError) as e:
print PROMPT_MSG_ERR + "\n"
main()
def main():
user_input = raw_input("{0}: ".format(PROMPT_MSG))
valid_input = validate_input(user_input)
if valid_input:
print "{0}*".format(" " * valid_input)
for i in range(0, valid_input)[1:-1]:
print "{0}*{1}*".format(
(" " * (valid_input - i)),
(" " * (i + (i-1))),
)
print " *" * valid_input
if __name__ == '__main__':
main()
Related
I'm writing a python script where I find the average of the sum of three numbers. I am using arguments for inputting the numbers. I need to finish the script by printing out error messages.
If I enter something like:
avg3 3 5
avg3 3 4 5 6
avg3 3 one 5
it needs to print an error telling me how to use it.
Here is the start of the script:
def main():
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
num3 = int(sys.argv[3])
avg = (num1 + num2 + num3)/3
print("The average of " +str(num1) + " " + str(num2) + " " + str(num3) + " " + "is " + str(round(avg,2)))
Edit:
For checking forcing an input of 3 numbers, and error checking:
def main():
if len(sys.argv) != 4:
print("You did not enter the correct amount of arguments")
else:
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
num3 = int(sys.argv[3])
avg = (num1 + num2 + num3)/3
print(f"The average of {num1} {num2} {num3} is {round(avg, 2)}")
except (UnboundLocalError, IndexError) as e:
# When you don't pass any args
print("You need to pass arguments")
print(f"($ python avg.py 3 1 2)\n Error = {e}")
except ValueError as e:
# You need to use numbers
print(f"You need to pass arguments as ints")
print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")
print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")
See the below for explanation:
len(sys.argv) will be 4 when there are 3 arguments (try print(sys.argv) for exploring this)
You could use a try statement to catch and except two common exceptions when passing args:
def main():
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
num3 = int(sys.argv[3])
avg = (num1 + num2 + num3)/3
print(f"The average of {num1} {num2} {num3} is {round(avg, 2)}")
except (UnboundLocalError, IndexError) as e:
# When you don't pass any args
print("You need to pass arguments")
print(f"($ python avg.py 3 1 2)\n Error = {e}")
except ValueError as e:
# You need to use numbers
print(f"You need to pass arguments as ints")
print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")
try will run a block, and except will run when it's listed exceptions are met in the try block (exiting the try loop).
You could also simplify your code to:
nums = [int(x) for x in sys.argv[1:4]]
avg = sum(nums)/3
And access your numbers with
# Same as nums1
nums[0]
and change the length of incoming arguments to anything >= 1 (if you want):
def main():
try:
nums = [int(x) for x in sys.argv[1:len(sys.argv)]]
avg = sum(nums)/len(nums)
print(f"The average of {', '.join([str(x) for x in nums])} is {round(avg, 2)}")
except (UnboundLocalError, IndexError, ZeroDivisionError) as e:
# When you don't pass any args
print("You need to pass arguments")
print(f"($ python avg.py 3 1 2)\n Error = {e}")
except ValueError as e:
# You need to use numbers
print(f"You need to pass arguments as ints")
print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")
If you are talking about catching the one arg as an error, you could simply catch a value error.
def main():
try:
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
num3 = int(sys.argv[3])
avg = (num1 + num2 + num3)/3
print("The average of " +str(num1) + " " + str(num2) + " " + str(num3) + " " + "is " + str(round(avg,2)))
except ValueError:
print("All your values need to be ints")
This will ensure that anything outside of a number being passed in as an arg would result in the message All your values need to be ints.
This won't catch any other errors, so you will have to catch them separately. For instance, your first example where you only pass 2 values won't work since there is no num3, but I'm assuming that isn't what you are asking about here.
So I'm trying to make a calculator but when i do plus (also with other things but for example) it does work but after the outcome comes it asks for number 2 again, I just want the code to start again.
this is the plus piece of the code:
q = input(str("Wil je de bewerkingsteken legende zien? (j/n): "))
if q == "J" or q == "j" :
print ("\nplus = + ")
print ("min = -")
print ("maal = X")
print ("delen door = :")
print ("quadrateren = Q")
print ("tot de kracht van = P")
print ("Worteltrekken = W")
print ("Procent = %")
num1 = float(input("\n Nummer 1: "))
bew = input("\n Bewerkingsteken: ")
num1_word = (str(num1))
if bew == "+" :
plus_num2 = input(float("\nNummer 2: "))
plus_num2_con = (str(plus_num2))
plus_out = (num1 + plus_num2)
plus_out1 = (str(plus_out))
print ("\n" + num1_con +" + " + num2_con + " = " + plus_out1)
First, you write the input wrong for plus_num2. Try this;
plus_num2 = float(input("\nNummer 2: "))
Second, you define the number's name different from last print function. Try This;
print ("\n" + num1_word +" + " + plus_num2_con + " = " + plus_out1)
Third, if you want to start the code again you can add while True on first line.
So i've been trying to create a calculator with more complex structure. The problem that am facing is that i'm trying to create a function that calls another function, i know it seems unneccesary but it will be needed in the future. I have a problem calling the function.
class Calculator:
class Variables:
# Start by defining the variables that you are going to use. I created a subclass because I think is better and
# easier for the code-reader to understand the code. For the early stages all variables are going to mainly
# assigned to 0.
n = 0 # n is the number that is going to be used as the main number before making the math calculation
n_for_add = 0 # n_for_add is the number that is going to added to "n" in addition
n_from_add = 0 # n_from_add is the result from the addition
self = 0
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
except ValueError: # if the value is not an integer it will raise an error
print("you must enter an integer!") # and print you this. This will automatically kill the program
self.n = n
self.n_for_add = n_for_add
n_from_add = n + n_for_add # this is actually the main calculation adding n and n_for_add
self.n_from_add = n_from_add
print(str(n) + " plus " + str(n_for_add) + " equals to " + str(n_from_add)) # this will print a nice output
def subtraction():
try:
nu = int(input("enter number: "))
nu_for_sub = int(input("What do you want to take off " + str(nu) + " ? "))
except ValueError:
print("you must enter an integer!")
nu_from_sub = nu - nu_for_sub
print(str(nu) + " minus " + str(nu_for_sub) + " equals to " + str(nu_from_sub))
# this is the same as addition but it subtracts instead of adding
def division():
try:
num = int(input("enter number: "))
num_for_div = int(input("What do you want to divide " + str(num) + " off? "))
except ValueError:
print("you must enter an integer!")
num_from_div = num / num_for_div
print(str(num) + " divided by " + str(num_for_div) + " equals to " + str(num_from_div))
# same as others but with division this time
def multiplication():
try:
numb = int(input("enter number: "))
numb_for_multi = int(input("What do you want to multiply " + str(numb) + " on? "))
except ValueError:
print("you must enter an integer!")
numb_from_multi = numb * numb_for_multi
print(str(numb) + " multiplied by " + str(numb_for_multi) + " equals to " + str(numb_from_multi))
# its the same as others but with multiplication function
def choice(self):
x = self.addition()
self.x = x
return x
choice(self)
Hope it will help you.
Code modified:
class Variables:
def addition(self):
try:
n = int(input("enter number: ")) # user enters the n value
n_for_add = int(input("What do you want to add on " + str(n) + " ? ")) # user enters the n_for_add value
return n + n_for_add
except ValueError:
# if the value is not an integer it will raise an error
pass
def choice(self):
x = self.addition()
self.x = x
return x
objectVariables = Variables()
print objectVariables.choice()
I hope this it may serve as its starting point:
def div(x, y):
return x / y
def add(x, y):
return x + y
def subs(x, y):
return x - y
def do(operation, x, y):
return operation(x, y)
print do(add, 4, 2)
print do(subs, 4, 2)
print do(div, 4, 2)
I'm working on this problem, that reads as follows:
Problem: Write a function that draws a pyramid on your screen. The function needs two arguments. The first is the height of the pyramid. The second argument is optional: if not supplied, the symbol "#" should be used to draw the pyramid. Otherwise, if the users enters " * " for example, the pyramid should consist of asterisks.
Attempt: I wrote this program:
def main():
h = int(input("Please enter the height of the pyramid: "))
symbol = str(input("Enter the desired symbol or press enter for standard (#): "))
def pyramid(h,symbol):
if symbol == "" or symbol == "#":
for i in range(h):
pyr = print(" " * (h-i - 1) + "#" * (2 * i + 1))
return pyr
else:
for i in range(h):
pyr = print(" " * (h-i - 1) + symbol * (2 * i + 1))
return pyr
print()
main()
But this is not working properly when I try to call this. Can someone point out my mistakes? Also, I'm not sure how to deal with the 'optional' property of the function. Should I stick to my approach or is there a better way to define that ?
your logic is fine, you can try
def pyramid(h,symbol):
if symbol == "" or symbol == "#":
for i in range(h):
print(" " * (h-i - 1) + "#" * (2 * i + 1))
else:
for i in range(h):
print(" " * (h-i - 1) + symbol * (2 * i + 1))
print()
pyramid(5, "#")
#
###
#####
#######
#########
your problems:
pyr = print(" " * (h-i - 1) + "#" * (2 * i + 1)) .... print function return None, then pyr store None
return pyr statement return pyr variable content and finish pyramid function
pyramid function isn't calling never
Improving code
you can remove unnecessary if,
def pyramid(h,symbol="#"):
for i in range(h):
print(" " * (h-i - 1) + symbol * (2 * i + 1))
print()
pyramid(5)
you can return a str
def pyramid(h,symbol="#"):
out = ""
for i in range(h):
out += (" " * (h-i - 1)) + (symbol * (2 * i + 1)) + "\n"
return out
print(pyramid(5))
or, online solution
def pyramid(h,symbol="#"):
return "\n".join((" " * (h-i - 1)) + (symbol * (2 * i + 1)) for i in range(h))
print(pyramid(5))
So I am trying to run a program on python3 that asks basic addition questions using random numbers. I have got the program running however, I wanted to know if there was a way I could count the occurrences of "Correct" and "Wrong" so I can give the person taking the quiz some feedback on how they did.
import random
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
else:
print ('Wrong.')
You could use a dict to store counts for each type, increment them when you come across each type, and then access it after to print the counts out.
Something like this:
import random
stats = {'correct': 0, 'wrong': 0}
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
stats['correct'] += 1
else:
print ('Wrong.')
stats['wrong'] += 1
print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])
import operator
import random
def ask_float(prompt):
while True:
try: return float(input(prompt))
except: print("Invalid Input please enter a number")
def ask_question(*args):
a = random.randint(1,100)
b = random.randint(1,100)
op = random.choice("+-/*")
answ = {"+":operator.add,"-":operator.sub,"*":operator.mul,"/":operator.div}[op](a,b)
return abs(answ - ask_float("%s %s %s = ?"%(a,op,b)))<0.01
num_questions = 5
answers_correct = sum(map(ask_question,range(num_questions)))
print("You got %d/%d Correct!"%(answers_correct,num_questions))