How to start with the number 1 in a for loop? - python

I want the first output to be "Enter the burst time of process 1" instead of "process 0". How to i do this?
num = int(input('Enter the number of processes: '))
for i in range(num):
b = input('Enter the burst time of process ' + str(i) + ': ')
a = input('Enter the arrival time of process ' + str(i) + ': ')

Python's range function returns integers starting between 0 and the given number if there is no starting parameter.
For instance:
for i in range(3):
print (i)
returns:
0
1
2
if you want to alter your code to print the range starting from 1 and inclusive of the given input, you may consider slightly changing the function to this:
num = int(input('Enter the number of processes: '))
for i in range(1,num+1):
b = input('Enter the burst time of process ' + str(i) + ': ')
a = input('Enter the arrival time of process ' + str(i) + ': ')
If you don't want your range to be inclusive of the given integer you can just do it like this:
num = int(input('Enter the number of processes: '))
for i in range(1,num):
b = input('Enter the burst time of process ' + str(i) + ': ')
a = input('Enter the arrival time of process ' + str(i) + ': ')

For loops work like so:
for [variable] in range(start, end, increment)
per your example, you would like to start at 1, and end at 5 for example
for [variable] in range(1, 5)
the values will display
1
2
3
4
End value always is 1 less because it counts 0, so you want to add +1 to the end if you want the exact number.

Related

The Sum of Consecutive Numbers

I have to write a program which asks the user to type in a limit. The program then calculates the sum of consecutive numbers (1 + 2 + 3 + ...) until the sum is at least equal to the limit set by the user.
In addition to the result it should also print out the calculation performed. I should do this with only a while loop, no lists or True conditionals.
limit = int(input("Limit:"))
base = 0
num = 0
calc = " "
while base < limit:
base += num
num += 1
calc += f" + {num}"
print(base)
print(f"The consecutive sum: {calc} = {base}")
So for example, if the input is 10, the output should be 10 and underneath that should be "The consecutive sum: 1 + 2 + 3 + 4 = 10." If the input is 18, the output should be 21 and underneath that should be "The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21."
Right now I can get it to print the final result (base) and have gotten it to print out the calculation, but it prints out one integer too many. If the input is 10, it prints out 1 + 2 + 3 + 4 + 5 when it should stop before the 5.
I would avoid the while loop and use range instead. You can derive the value of the last term with arithmetic.
If the last term is 𝑛, then the sum will be 𝑛(𝑛+1)/2, which must be less or equal to the input limit. Resolving this equation to 𝑛 given the limit, we get that the 𝑛 is ⌊√(1 + 8β‹…limit) βˆ’ 1) / 2βŒ‹
So then the program can be:
limit = int(input("Limit:"))
n = int(((1 + 8 * limit) ** 0.5 - 1) / 2)
formula = " + ".join(map(str, range(1, n + 1)))
total = n * (n + 1) // 2
print(f"The consecutive sum: {formula} = {total}")
One way that came to my mind is concatenating values for each iteration:
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
calculation = 'The consecutive sum: '
while base < limit:
calculation += f"{num} + "
base += num
num += 1
print(f"{calculation[:-3]} = {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
## 21
The other way is printing value on each iteration without new line in the end (but you have additional + sign in the end here):
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
print('The consecutive sum: ', end='')
while base < limit:
print(f"{num} + ", end='')
base += num
num += 1
print(f"= {base}")
print(base)
#> Limit:18
## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 + = 21
## 21
There's probably a more efficient way to write this but this was what came to mind...
sum = 0
long_output = []
for i in range(limit + 1):
sum += i
long_output.append(str(i))
print("The consecutive sum: {} = {}".format(' + '.join(long_output), sum))
Keep putting stuff in an list and then join them afterwards. i has to be casted to a str type since join is just for strings
NOTE: the output starts at 0 to account for limit being potentially 0 (I don't know what your constraints are, if any)
EDIT: made updates based on #Copperfield's recommendation
You are/were very close. Try rearranging the follow of execution in your while statements. I also find this assignment hard. Try moving you calc line as the first statement after your 'while'.
One other way is to add an if statement:
if base< num :
calc += f" + {num}"
Here is a example to print the calculation
limit = int(input("Limit:"))
base = 0
num = 1
num_total = 0
msg = ""
while base < limit:
msg = msg + str(num) + "+"
base += num
num += 1
msg = msg[:-1] + "=" + str(limit)
print(msg)
if limit = 21 then the output would be
1+2+3+4+5+6=21

how to print output from a while loop from a for loop for each iteration

I know I need a for loop, I am trying to print the input number(as a maximum) and then print the number of steps it took to reach 1. The current program prints the input number and the nember of steps for that input number, I need it to print every input number and corresponding steps for each number to 1 with related steps. If i input 2 it should say it 2 takes 1 steps then 1 takes 0 steps.
n = int(input('n? '))
n_steps = 0
num=n
while n > 1:
n_steps+=1
if n % 2 == 0:
n = n // 2
else:
n = n * 3 + 1
print(str(num) + ' takes ' + str(n_steps) + ' steps')
are you trying to do something like this?
num = int(input('n? '))
for i in range(num, 0, -1):
n_steps = 0
n = i
while n > 1:
n_steps += 1
if n % 2 == 0:
n = n // 2
else:
n = n * 3 + 1
print(str(i) + ' takes ' + str(n_steps) + ' steps')

Python Factorial Program - Printing the Equation

I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120

Python 3.4.2 | Loop input until set amount

Learning the basics of python and I am running across a problem. I'm sure it is a simple fix. I'm trying to get my program to get 20 different inputs before calculating the min, max, etc.
def main():
number = valueInput()
display(number)
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
def display(number):
print("The lowest number is:", min(number))
print("The highest number is:", max(number))
print("The sum of the numbers is:", sum(number))
print("The average number is:", sum(number)/len(number))
main()
I can get it to work by repeating this line:
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
to the 20th number but there must be a way that makes it shorter and cleaner. Again I am a beginner so any explanation would be much appreciated.
All you have to do to fix your program is remove four spaces:
def valueInput():
print("Please enter 20 random numbers")
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
The last line in the block above has been unindented by one level. Instead of returning after the first time through the loop, it lets the loop complete, and then returns the resulting list.
Also you can change your:
values = []
for i in range(20):
value1 =(int(input("Enter a random number " + str(i + 1) + ": ")))
values.append(value1)
return values
part with:
values = [int(input("Enter a random number " + str(x + 1) + ": ")) for x in list(range(20))]
return values
You can check out build in functions

Add integers to a list?

I am trying to ask the user for several values for temperatures of several month by the "monthtemp" input and then add all the values to a list and in the end print out the average for the whole year.
count = 1
loops = int(input("How many years?: "))
listofmonthtemperatures= list()
while count < loops:
for i in range(1,loops+1):
count += 1
year = input("Which is the " + str(i) + ": year?: ")
for j in range (1,13):
monthtemp= int(input("Month " + str(j) + ": "))
listofmonthtemperatures.append(monthtemp)
total= sum(listofmonthtemperatures)
averagetempforyear= total / 12
print("The average temperature for", year, "is", averagetempforyear)
But I get the message year is not defined, but haven't I defined it as whatever the user inputs? And second, will this work? Why can't append simply append the value to listofmonthtemperatures?
I copy/pasted your code and it worked just fine. Maybe this was a typo but your for loops weren't properly indented. I'm running 3.4.3 btw.
count = 1
loops = int(input("How many years?: "))
listofmonthtemperatures= list()
while count < loops:
for i in range(1,loops+1):
count += 1
year = input("Which is the " + str(i) + ": year?: ")
for j in range (1,13):
monthtemp= int(input("Month " + str(j) + ": "))
listofmonthtemperatures.append(monthtemp)
total= sum(listofmonthtemperatures)
averagetempforyear= total / 12
print("The average temperature for", year, "is", averagetempforyear)
Above is the working code with the proper indentation.

Categories