Do-while in Python 3x - python

Evening Stack Overflow. Im a beginner in Python, which is why i decided to come on here for some help. Specifically, i'm having trouble understanding "do-while loop".
Here is the assignment i where given:
[Design the logic for a program that allows the user to enter a number. The program will display the sum of every number from 1 through the entered number. The program will allow the user to continuously enter numbers until the user enters 0.]
Here is my code without the "Do-while loop":
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display the total \ sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
print ('\nThank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
Works great. Essentially do what i want it to do.
Now, from the assignment......it states:
The program will allow the user to continuously enter numbers until the user enters 0.
So here is my code/attempt for that:
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display \
the total sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
def equation_run(EQ):
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
zero = 0
while zero < user_number:
print (equation_run)
elif zero == user_number:
print ('Thank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
When running this code, i get a syntax error. It highlights the elif part. Ive tried trial-and-error, but cant seem to get it to work. Please help.
Any comments/suggestion would be greatly appreciated. Thank you in advance and good day.

elif comes after an if, not a while. Replace it with a simple if:
while zero < user_number:
...
if zero == user_number:
...

something like:
while True:
number = int(input("Enter a number: "))
if number == 0:
break
print(0.5*number*(number+1))
should work

Related

we need to write a prorgam that asks a user to enter multiple numbers and ends the while loop with -1.then work out the average of numbers provided

we have been tasked with writing a program in python asking a user to enter multiple numbers.
the subject is while loops,so we can only make use of while loops and if statements.
when the user wants to stop the entry of numbers,the user then needs to type '-1'.
once that has been done,the program must return the average of the numbers entered by the user.
this is what i have so far:
#task 13-while.py
#first the program will explain to the user that the user can keep
#entering numbers until -1 occurs.
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program'''))
num_count = 0
while num > -1:
num_count = num_count + 1
average = sum(num)/num_count
if num == -1:
print("the average of the numbers you have entered is"+ average)
extremely inexperienced with python,all help will be greatly appreciated.
You need to put the input into the while and then only when the loop is over calculate the averageLike this:
num = int(input("enter numbers and then -1 to stop: "))
num_count = 1
sum = num
while num!=-1:
num = int(input("another number: "))
num_count+=1
sum+=num
print(sum/num_count)
In order for it to work you need to add an input() call inside the while loop like in the code bellow :
count = 0
sum = 0
num = int(input('''please enter any number of your choice\n
please enter -1 to stop entry and run program\n'''))
while num != -1:
sum += num
count +=1
num = int(input('''Give another integer\n'''))
print("the average of the numbers you have entered is", sum/count)
Personal advice : I would suggest for you to read more tutorials or ask your peofessor for more work

Why cant i sum up all of my values (user values) problem with while?

I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.

Why does my code run quicker on my phone than my laptop?

I'm beginning to learn python and I've just finished my first project, which was the collatz sequence, which is "If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process until you reach 1."
Here is my code, it's not very long:
import sys
def integer(): #Asks for input and checks whether positive integer
while True:
number = input("Enter a positive, whole number:")
try:
number = int(number)
if number > 0:
break
else:
raise ValueError
except ValueError:
print("That's not right! \n Please enter a positive, whole number")
return number
number = None
def collatz():
global number
print(number)
while number > 1:
if number % 2 ==0:
number = number // 2
else:
number = number * 3 + 1
print(number)
while True: #loop so that you can try again
number = integer()
collatz()
repeat = input("Try again? Y/N").upper()
while repeat != "Y" and repeat != "N": #Only Y/N are valid
repeat = input("Try again? Y/N")
if repeat == "N":
sys.exit() #end program if N selected
else:
pass #Reloops to try again
I ran this code on an app called "QPython3" on my Google Pixel XL (Up to 2.4 GHz), running Android 7.1.1 and also my base model MacBook Pro (Retina, 13-inch, Early 2015)(2.7GHz).
The MacBook took multiple minutes to reach 1 when I used an absurdly large number such as 10^100, but my phone did it almost instantaneously.
I don't understand why this would be the case. Shouldn't the proper computer be better in every way?
(If you want to give feedback on the overall effectiveness of my code, that is appreciated, but probably not worth your time as I'm very new and would likely not understand things too well. I'm just trying to make code that works at this stage)

Python Calculator: Several options, changing the number

Hello I am new to python and I am trying to do an assignment but I couldn't get the needed output I am supposed to
get. Can any one suggest me what I am missing? Thank you!
Assignment:
The last exercise in this chapter continues with the exercise from the last chapter, the calculator. In this exercise, expand the existing code by implementing the following new features: (A) Calculator does not automatically quit when the result is given, allowing user to do new calculations. The user has to select "6" in the menu to exit the program. (B) The calculator shows the selected numbers in the main menu by printing "Current numbers:" and the user-given input. By selecting "5" in the calculator menu, the user can change the given numbers.
When implemented correctly, the program prints out following:
Again, implement the program within one large while True-segment, which is terminated with break if the user selects the option "6".
Example output
Calculator
Give the first number: 100
Give the second number: 25
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 100 25
Please select something (1-6): 5
Give the first number: 10
Give the second number: 30
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 10 30
Please select something (1-6): 1
The result is: 40
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 10 30
Please select something (1-6): 6
Thank you!
MY code:
print("Calculator")
while True:
selrction={1,2,3,4,5,6,}
value1 = int(input("Give the first number: "))
value2 = int(input("Give the second number: "))
print("(1) +\n(2) -\n(3) *\n(4) /\n(5)Change numbers\n(6)Quit")
print("Current numbers: ",value1,value2)
selection=int(input("Please select something (1-6): "))
if selection==1:
print("The result is: ",(value1+value2))
elif selection==2:
print("The result is: ",(value1-value2))
elif selection==3:
print("The result is: ", (value1*value2))
elif selection==4:
print("The result is: ",(value1/value2))
elif selection==6:
print("Thank you!")
break
elif selection==5:
print("Change numbers")
continue
else:
print("Selection was not correct.")
selection+=1
my output
Calculator
Give the first number: 100
Give the second number: 25
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 100 25
Please select something (1-6): 5
Change numbers
Give the first number: 10
Give the second number: 30
(1) +
(2) -
(3) *
(4) /
(5)Change numbers
(6)Quit
Current numbers: 10 30
Please select something (1-6): 1
The result is: 40
Give the first number: 6
Give the second number:
You need to use a flag (e.g. promptForNumbers) to determine whether to prompt for the values again in the loop. Set the flag to True at the very start before the loop, and only execute the value capture of inputs value1 and value2 if the flag is True. Once the numbers are captured, set the flag to False. Then, only set the flag to True again when option 5 is selected (change numbers).
Other points of note:
The continue statement is redundant, too, as there's nothing that follows the if/elsif/elsif/../else statement.
selrction={1,2,3,4,5,6,} statement is redundant (and misspelled), as next assignment to selection is another assignment, and there's no use in-between.
selection+=1 is also redundant, as it's not used.
casting input to integer int(input(value)), rather than float float(input(value)), will limit the accuracy of the calculator
changed indentation to be consistent with expected Python format
there's no error handling for division-by-zero processing (so if 0 is entered as the second number, then division / selected, it'll exit with an exception)
So here's the code with changes as described above:
print("Calculator")
# Flag to indicate whether user should be prompted for input numbers
promptForNumbers = True
while True:
if promptForNumbers:
value1 = float(input("Give the first number: "))
value2 = float(input("Give the second number: "))
# Set prompt flag false to prevent re-prompting for numbers upon next loop
promptForNumbers = False
print("(1) +\n(2) -\n(3) *\n(4) /\n(5)Change numbers\n(6)Quit")
print "Current numbers: %s, %s" % (value1, value2)
selection = int(input("Please select something (1-6): "))
if selection == 1:
print("The result is: %s" % (value1 + value2))
elif selection == 2:
print("The result is: %s" % (value1-value2))
elif selection==3:
print("The result is: %s" % (value1*value2))
elif selection==4:
print("The result is: %s" % (value1/value2))
elif selection==6:
print("Thank you!")
break
elif selection==5:
# Set prompt flag so that numbers will be requested upon next loop
promptForNumbers = True
else:
print("Selection was not correct.")

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories