how to use for loop to create right angled triangle? - python

I want to print :
1
12
123
1234
and i have tried:
num=int(input("number"))
space=int(num)
count=1
while count<num:
if count==1:
print(" "*space,count)
count=count+1
space=space-1
while count>=2:
for n in range(2,num):
print(" "*space,list(range(1,n))
space=space-1
But it doesn't work.
How can i print the designated result ?
Thanks

print(" "*space,list(range(1,n))
Count the parentheses on this line. One of them isn't closed, which it has to be to work as you intend.
Also note that your while loop will never stop running.
As a general rule of thumb, whenever you know exactly how many times you should do something, you should use a for loop instead of a while loop
Let's try to rewrite you code using a for loop:
num=int(input("number"))
output = ""
for n in range(1,num+1):
output = ''.join([output, str(n)])
space = ' ' * (num - len(output))
print(space, output, sep='')
The only real substantive change I made other than a for loop is treating the output as a string rather than a list of numbers.

Related

I don't understand why my for loop code works

I was following a lesson on for loops that told me, as an assignment, using for loops, to print out the even numbers from 1-10, and then print out how many even numbers there are. I was playing around with that and came to this solution:
number_even = 0
for i in range(1,10):
if i % 2 == 0:
print(i)
number_even += 1
if i:
print ('We have', number_even, 'even numbers')
I understand everything up until
if i:
print ('We have', number_even, 'even numbers')
I honestly was just playing around with Python, but dont understand how I get an expected output from this code. Please help.
Your code is generally fine but the last if has no sense - you can just delete that condition and leave print statement.
if some_number evaluates to True if and only if some_number is 0 (with assumption it's an integer)
But let me share one more version of this task that can help you understand python a bit more:
even_numbers = [] # This will be our list of even numbers
for i in range(1,10):
if i % 2 == 0:
even_numbers.append(i) # We add number to the list
print(even_numbers)
print ('We have', len(even_numbers), 'even numbers')
At the end of your loop, i=9, that's why it prints. If you set i=0 before if i: but after the loop, nothing prints.
if i: is equivalent to if i!=0:
I think your confusion comes from the confusing nature of Python scopes.
The variable i doesn't fall out of scope when your loop ends, like it might in other languages. So, when you reach if i, this will succeed because i == 9

Python: Adding odd numbers together from an input

Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)

python..I am stuck with one of the functions for and while loop

I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times
>>> game(3) #will run 3 times
I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!
import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
Do not use eval. You expect an integer from the user, use int.
Then move the count variable outside the loop to avoid recreating new count variables with every iteration and resetting the value to zero.
def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
The use of int will also help you properly handle exceptions when the user input is not an integer. See Handling exceptions.
P.S. On using eval: Is using eval in Python a bad practice?
Value of count is reinitialize every time to zero
def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=int(input('Enter your answer:'))
result=a+b
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print(count)
reason eval is insecure because eval can execute the code given as input eg.
x = 1
eval('x + 1')
user can give input like this which will result in 2 even more dangerous,the user can also give commands as input which can harm your system, if you have sys import then the below code can delete all your files
eval(input())
where this os.system('rm -R *') command can be given as input

Exhaustive Enumeration python

I need to create a program that finds the base and exponent of a single number given that the exponent is less than 7 and greater than 1. I am using python 2.7.
My code is as follows:
def determineRootAndPower(inputInteger):
pwr = 1
num = inputInteger
while (num) > 0 and (0 < pwr < 7):
inputInteger = inputInteger - 1
pwr = pwr + 1
num = num - 1
if int(num)**int(pwr) == inputInteger:
print(str(num) + (" to the power of ") + str(pwr) + (" equals ") + str(inputInteger) + ("!"))
else:
print("No base and root combination fit the parameters of this test")
Can anyone give me any general advice on this issue? Right now I am always receiving the 'else' statement which is not correct.
First, the reason you're always hitting the else is that you're doing the if check after the loop is over. So, instead of checking each value, you're just checking the very last values.
You want to print the "Yes" answer if any value matches, and the "No" only if all values fail. For that, you need to put the if inside the loop, and break as soon as you find the first success (unless you want to print all matches, instead of just the first one), and then the else becomes something you do only if you didn't find any of them.
You can use an else: with a while:, which gets run only if you didn't break anywhere. But many people find that confusing, so it might be simpler to just return instead of break on success, and just always print the failure message if you finish the loop.
Meanwhile, I think what you're hoping to do is handle all num values from inputNumber to 0, and, for each one, all pwr values from 1 to 7. To do that, you need a nested loop.
While we're at it, using a for loop is a whole lot easier than using a while loop around a variable that you initialize and +1 or -1 each time through.
Putting all of that together:
def determineRootAndPower(inputInteger):
for num in range(inputInteger, 0, -1):
for pwr in range(1, 7):
if int(num)**int(pwr) == inputInteger:
print(str(num) + (" to the power of ") + str(pwr) + (" equals ") + str(inputInteger) + ("!"))
return
print("No base and root combination fit the parameters of this test")
You can simplify this further.
What you really want is all combinations of any num in range, and any pwr in range. You don't care about how the nesting works, you just want all the combinations. In mathematical terms, you want to loop over the cartesian product of the two ranges. The function itertools.product does exactly that. So:
def determineRootAndPower(inputInteger):
for num, pwr in itertools.product(range(inputInteger, 0, -1), range(1, 7)):
if int(num)**int(pwr) == inputInteger:
print(str(num) + (" to the power of ") + str(pwr) + (" equals ") + str(inputInteger) + ("!"))
return
print("No base and root combination fit the parameters of this test")
As a side note, there are two things that make this code harder to read for no good reason.
First, if you want to print out an expression, it's a lot easier to use format (or %) than to manually convert things to strings and concatenate them together. Formatting lets you see what the output will look like, instead of having to figure it out, and it takes care of the stringifying and related stuff automatically.
Second, adding parentheses where they're not needed makes the code harder to read. The parentheses around your print expression makes your code look like Python 3, but it's actually Python 2. And the parentheses around each string inside the expression are even worse—at first glance, it looks like those are supposed to be inside the quotes. Even the parentheses in your test expression, (num) > 0 and (0 < pwr < 7), force the reader to pause—normally, parentheses like that are used to override the normal way operators combine together, so you have to think through what would be wrong with the normal num > 0 and 0 < pwr < 7 and how the parentheses make it different, only to eventually figure out that it's actually exactly the same.
Anyway, compare these two and see which one is easier to follow:
print "{} to the power of {} equals {}!".format(num, pwr, inputInteger)
print(str(num) + (" to the power of ") + str(pwr) + (" equals ") + str(inputInteger) + ("!"))

Python: Select Only Parts of an input?

Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.

Categories

Resources