What is the output of the loop in python? - python

This is a loop in PYTHON 3.X.
for i in range(2, 2):
print(i)
The result that I got after running this program was a blank console.
What type of output we get from this loop.

The range of numbers returned are integers from start to stop. ( the first param being start, and second being stop when 2 are given)
It includes the start int, but not the stop int.
hence, range(2,2) contains no numbers in between.
range(2,4) returns 2,3 but not 4.
Documentation here.

The reason you're getting blank output is because what the range() function does.
The first argument in the range() function tells the function which number to iterate to.
So, if this was your code:
for i in range(2):
print(i)
Then your output would be:
0
1
It starts from 0 and prints two numbers, because of the two.
However, the second parameter in your code tells it what to count by. For example, you added a 2 for the second parameter. This tells the program to skip count by 2, and since you have only 2 output in the first place, the program doesn't print anything
Read up on range in python 3.
Hopefully this helps!

Related

Can somebody explain me this recursion?

def name(n):
if n>0:
name(n-1)
name(n-1)
print(n)
name(5)
How this is generating 1,1,2,1,1,2,3.....so on output? like which function is working first or both working simultaneously and how n is printing like this.
Try with smaller numbers. For example if you run name(1) it will just print 1. becase two functions in the middle will just return. If you write name(2) it will run the first inner funtion, which will print 1(like I said previously). Second function will do the same and last statement will print 2. So the output is 1 1 2. If you go for name(3) it will just the same as name(2) but twice and will print 3 at the end (1 1 2) (1 1 2) 3. name(4) will do name(3) twice and print 4 at end and so on
Another way to lok at this is in reverse. eg. you look at the smallest number:
name(0): Prints nothing, thus ""
name(1): calls name(0) twice, and then prints 1, thus "1"
name(2): calls name(1) twice, and then prints 2, thus "112"
name(3): calls name(2) twice before it prints 3, thus "1121123"
name(4): calls name(3) twice before it prints 4, thus "112112311211234"
name(5): calls name(4) twice before it prints 5, thus "1121123112112341121123112112345"
Finally the clue is that there is no spcial treatment of functions that recurse. Every call to a function, even print, will wait for that to return and then continue on the next line as long as the statement didn't include a return in which it would return. that name(5) ends up calling itself with different versions of n at different levels is no problem because each of them has their own version of n that is unique to that call.
Hello I attached this image that shows explanation in details

Why my return statement is not showing any output?

I was trying to solve the following problem: Draw a star pattern that increases in every step (1st step: 1 star, 2nd step: 2 stars). E.g.
*
**
I am not sure why my code is not showing any output when I am writing return? When I am writing print, it is giving me the star output but also giving me None. May I know why return or print are not working properly? I am using Python 3.7. My code is:
def string(inp):
for i in range (inp):
return i*"*"
print (string(5))
range starts at 0, and return terminates a function, so that means string will always return an empty string.
Here's one possible option for getting your expected result:
def stars(n):
for i in range(1, n+1): # Add one to start and stop
print(i * "*") # Print inside the function
stars(2) # Don't print outside the function
Output:
*
**
If you need to print outside the function, you could use a generator:
def stars(n):
for i in range(1, n+1):
yield i * "*" # "yield" is like "return" but can be used more than once
for s in stars(2):
print(s) # Print each string that gets yielded
# Or print all at once, using the "splat" unpacking operator
print(*stars(5), sep='\n')
Using return won't print an output, use something like this:
def string(inp):
for i in range (inp):
print(i*"*")
string(5)
also this will only print 4, if you make it
for i in range(inp + 1):
It will work as intended,
hope this helps!
I will translate the code to plain English, as explicitly as I can:
Here are the rules that take a value `inp` and compute the `string` of that `inp`:
Letting `i` take on each integer value from 0 up to but not including `inp`:
We are done. The `string` of `inp` is equal to the string '*' repeated `i` times.
Compute the `string` of `5` and display it.
Hopefully the problem is evident: we can only be done with a task once, and i is equal to 0 at that point, so our computed value is an empty string.
When I am writing print, it is giving me the star output but also giving me None
From the described behaviour, I assume that you mean that you tried to replace the word return in your code with print, giving:
def string(inp):
for i in range (inp):
print(i*"*")
print (string(5))
That produces the triangle, of course, except that
Since i will be equal to 0 the first time through the loop, a blank line is printed; and since i will be equal to 4 the last time through the loop, there is no ***** line.
At the end, None is printed, as you describe. This happens because the value computed by string is the special value None, which is then printed because you asked for it to be printed (print(string(5))).
In Python, each call to a function will return a value when it returns, whether or not you use return and whether or not you specify a value to return. The default is this special None value, which is a unique object of its own type. It displays with the text None when printed, but is different from a string with that text (in the same way that the integer 5 is different from the string "5").
May I know why return or print are not working properly?
They are working exactly as designed. return specifies the result of calling the function, and can only happen once per function, and does not cause anything to be displayed. print displays what it is given.
If you wish to return multiple values from a call, then you need to work around that restriction - either by using a generator instead (as in #MadPhysicist's or #wjandrea's answers), or by using some single, structured datum that contains all those values (for example, a list, or a tuple).
A a re-entrant function that preserves state between calls is a generator. To make a generator function, change the keyword return to yield:
def string(n):
for i in range(n):
yield (i + 1) * '*'
Calling this version of string will return a generator that yields a new line of your desired output at each iteration.
To print:
for line in string(5):
print(line)
To print all at once:
print('\n'.join(string(5)))

Python: How can I use a for loop to execute my code 5 times?

I am new to python and working on basic functions and conditionals.
Here's an example of 1 function in my code:
def oddEven(oe):
if oe % 2 == 0:
print("number is even")
else:
print("number is odd")
There are 3 total functions in my code (omitted because unnecessary). The first two pass the value of the integer named first, and the last function takes two integer parameters and pass both first and second and checks the result.
Here is how I'm recalling these and checking my code
first = 30
second = 60
oddEven(first)
minutes(first)
relation(first, second)
Instructions say:
Run the program five times using the provided first values and your chosen second values, and check your results. You can alternatively run the program once and use a for loop to execute your code five times.
If the values were for example 23, 33, 14, 31 I could just do:
oddEven(23)
oddEven(33)
oddEven(14)
oddEven(31)
Right? And then do the same for the second function and the third. How could I make a for loop for this?
This is simple way to do this :
list_values = [22,33,14,31]
for value in list_Values:
oddEven(value)
You’re right, you use a for loop in order to do that. The previous answers may have been able to iterate through the list for both the evenOdd and minutes functions, but they didn’t handle the case where you compare two consecutive values for your relation function.
Create a list of 5 numbers and iterate through it. Handling the case where you’re comparing two consecutive numbers against each other can be done with a simple if statement that stops executing once you’ve reached the second to the last element in the list.
If you’re not familiar with lists yet, think of them as ‘containers’ for your data; where you can systematically store and access each piece one at a time.
What’s happening in the code is the for loop iterates through the list one element at a time. The function range(n) takes in a number n, for an argument, and then creates a ‘range’ of numbers from 0 to n - 1.(Ex. range(2) will iterate through the for loop 2 times giving i a value of 0 on the first loop and 1 on the second.
An element from a list can be accessed with this notation: list[i], where i is a number that starts from 0 (therefore accessing the first element of the list) and ranges all the way up to the (length of the list - 1). So to access the third element in a list would be done like so: list[2].
The code below is pretty modular so you can add any amount of numbers to the numbers[] list and it should work, given that there is more then 1 number in the list. It’s a good practice to get in the habit of making your code as modular as possible, instead of hard coding in constants. This is done by passing the (length of the list) to the range(), which allows the for loop to iterate over any size list.
If you add only one number to the list ( ex. numbers = [42]), the only thing that would happen is that the code inside the if statement will not execute, as it requires there to be more than 1 number in the list. The oddEven and minute function should still work though. Go ahead and give that a try! Try adding more than 5 numbers to the list too.
numbers = [23, 33, 14, 21, 42]
for i in range(len(numbers)):
first = numbers[i]
oddEven(first)
minutes(first)
if i < (len(numbers) - 1):
second = numbers[i + 1]
relation(first, second)

when assigning to a variable list index out of range?

n = int(input())
numb = input()
lis = list(map(int, numb.split()))
lis.sort()
a = lis[n]
for i in (0,len(lis)):
if lis[i]=[a]
print (lis[i-1])
I tried this and when I enter input of 5 for n and the lis as 24689 it says there is an error in the line where a=lis[n] saying the list index is out of range.
The problem is probably with the line
for i in (0,len(lis)):
Lists are zero-based so the valid indexes are from 0 to len(lis) - 1. len(lis) is indeed out of range.
Also, notice that the above line of code means that i will receive only 2 values - 0 and len(lis). Is that what you really mean? If you meant to go over all the indexes, you will need to do
for i in range(len(lis)):
range(n) is an iterator that returns the values from 0 to n - 1.
There are several problems with this code. Firstly, you need to change your for statement to for i in range(0, len(lis)) because you're not currently calling the range function.
Also, on the first iteration, it will try to access index -1, which is the last element in the list. A better idea is to change your range function to range(0, len(lis) - 1), and changing the print statement on the last line to print(lis[i]) to fix the problem of receiving the last element by using the index -1.
P.S. Welcome to Stack Overflow!
Wow, Keep note that what you thought would happen on your third line wasn't the case and is 1 of the 2 problems of your error message. and that 1 problem was due to one single function you used which I have sequentially demonstration below;
I assume you were expecting each character of the string '24689' to be transformed to an integer by the map() function*, then converted to a list by the list() function*, then stored in the Variable ...lis... for later further usage. You were expecting something like [2,4,6,8,9] as Lis`.
Well you almost had that if not for your decision to use split() on Numb.
The Split function will run first and turn the '24689' into a
different iterable, in this case changing '24689' to a list ['24689'].
Then the map() will map every item in this iterable ['24689'] to an
integer. In this case only 1 item exist in the list which is '24689'.
So it maps that item as an integer.
Then the list() function stores this single item which is now an
integer in a list owned by the variable Lis. So you finally get
[24689]. And this is different from your [2,4,6,8,9] expectation.
As I've demonstrated above, so the cause of all this problem was your decision to use Split().
if you take away the split(), then;
the map() will no longer see just one Item but rather '2' '4' '6' '8'
'9' because a string '24689' is an iterable, with 5 individual items in
your case. So the map() runs over all these 5 items in your Numb string and
maps/transforms them to individual integers respectively. Then finally
the List() would have stored all these beautiful individual integers
in a list Owned by the variable Lis.And you get your desired [2,4,6,8,9] in return for the Variable Lis.
So the correct statement for that very line is:
lis = list(map(int, numb)) // This line should now produce [2,4,6,8,9]
The second problem of your error was the value you assigned to the index variable 'n' of list[n]. I assume you wanted to fetch the fifth item in the list. This 'n' is the linear count of items(in your case the individual numbers - 2,4,6,8,9). This counting start from 0 for the first letter instead of 1. Normally when you count items, the first letter is 1 but for index count in python list[n], the first letter is 0 instead of 1 so in your case the fifth item will be indexed as 4 since index count start from 0. So your 'n' input should be 4
These 2 solutions above solves your the specific error you mentioned.
BUT aside from your question above, your entire code will still run into another error even if the above solutions are implemented. This is Due to errors on these following lines as well:
On line 6:
for i in (0,len(lis)): //Wrong due to NO function name called before '(0, len(lis))'.
We will logically assume you want to use the range function
correct expression on LINE 6 is:
for i in range(0, len(lis)):
On Line 7:
if lis[i]=[a] //Three problems on this line...
First, you can't compare two objects with the operator '='. instead use '=='
Second, [a] is a meaningless value in your expression... Does comparing that to a number look right to you? I bet No. Remember [a] is not the same as the variable 'a'.
a = lis[n], while [a] = [lis[n]]
So the correct expression there should be 'a' and not '[a]'
Last, you need to add ':' after every "if", "for" or "while" expression..
Here is how LINE 7 should CORRECTLY look like,
if lis[i] == a:
All the above solutions should satisfy your need. So the complete correct code for your script should look like this:
n = int(input())
numb = input()
lis = list(map(int, numb))
lis.sort()
a = lis[n]
for i in range(0,len(lis)):
if lis[i] == a:
print (lis[i-1])

Python: Iterating a string with an int(variable) through a function

I'm an absolute beginner and have read many related topics but I just can't get my mind around it.
I try to create a function which iterates through the string s exactly "n" times.
s="hello"
n=2
If I simply type in
s[::n]
it does work, however, if I try to express this in a function everything goes haywire.
My function looks like this:
def printEvery(s,n):
for n in range(len(s)):
print(s[::n])
ValueError: slice step cannot be zero
I really don't get why it doesn't work in a function as in my head it only makes sense this way. I'd deeply appreciate any help.
E: Sorry for the format and thank you for the edit khelwood!
def printEvery(s,n):
for x in range(1, len(s) + 1):
print(s[::n])
printEvery("Hello", 2)
Not quite sure why you would ever need this though
As I already mentioned in the comment, range starts at 0, so you cannot slice a string to return every zero-th element.
Another problem with your function is, that the parameter "n" is immediately overwritten by the for loop, so no matter with what second argument you call printEvery, it will always print the same text. This is equivalent:
def printEvery(text):
for stepsize in range(1, len(text)):
print(text[::stepsize])
def printEvery(text):
for i in range(len(text)+1,1,-1):
print (text[::i])
Every for loop starts at 0
Range's instruction is
range([start], stop[, step])
in which it indicates that where should the number start, then when should it stop and how many steps should it undergo.
In this case, it starts at 11, as I wrote len(text)+1 and I supposed len(text) is 10. I told Python to stop when it reachs 1, and each time it is -1 each time so if you replace
print (text[::i])
#replace this line to this:
print i
This would be printed:
11
10
9
8
7
6
5
4
3
2
1
I hope it works for you. I am not really good at English so sorry for my bad English :)

Categories