Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I have a script that I wrote in python for testing out the sorting algorithms that I've implemented. The main part of the program asks the user to select one of the sort algorithms from a list. And then whether they would like to sort from a file of numbers or select a list of random numbers. I have it set up (I think) so that typing a number that's not in the first list of choices will just print "Bad choice" and try getting the number again.
[Edit] After taking the advice of the answer I changed a couple of the inputs to raw inputs. And I changed the structure of the program. It now works perfectly except it still prints out "Bad Choice" even after a success.
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
choices = {1:SelectionSorter,2:ComparisonSorter}
print "Please enter the type of sort you would like to perform."
print "1. Selection Sort\n2. Comparison Sort"
while(True):
try:
choice=input("Your choice: ")
for i in range(2):
if(choice==i+1):
choice2=fileOrRandom()
if(choice2=='A'):
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif(choice2=='B'):
num = input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
else:
raise Exception
else:
raise Exception
break
except Exception:
print "Bad Choice"
My issue is that it works as expected for the first part where it will return "bad choice" for a number that's not in the list, and it will get fileOrRandom(), but it still prints "Bad Choice" when selecting good values that should print out my results because sorter.timedSort(sorter.sort) executes my sorting algorithm and prints out a bunch of other things to the screen. Am I just missing something simple or is there a better way to deal with these nested options in a Python program?
use raw_input()
def fileOrRandom():
return raw_input("Would you like to read from file or random list? (A or B): ")
your while loop should look like this (after fixing the indentation)
while True :
choice=raw_input("Your choice: ")
for i in range(2):
if choice==i+1 and fileOrRandom()=="A" :
fileName=raw_input("Please Enter The Name of the File to sort: ")
sorter = choices[choice](fileName)
sorter.timedSort(sorter.sort)
elif choice==i+1 and fileOrRandom()=="B" :
num = raw_input("How many random numbers would you like to sort: ")
sorter = choices[choice](None,num)
sorter.timedSort(sorter.sort)
elif choice in ['q','Q']: break
else: print "Bad choice"
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
A number that equals to the sum of its own digits, where each digit raised to the power of number of digits. For example, 153 is an armstrong number
because 1^3+3^3+5^3=153
at here user enters a number
number=int(input("please enter a number: "))
Here in a while loop it puts the digits of the given number in numbers class
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
and then we want to put their qubes in qubes class
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
and now we calculate the sum of the qubes class members
result = sum(i for i in qubes)
I dont know why the if_code below doesnt work it just gives me false output I dont know why??
even when i enter 153 it prints false
if result==number:
print("true")
else:print("false")
To sum-up all suggestions from the comments:
Your main problem is:
When you create the numbers list you use number = int(number/10). This changes the number variable itself until it is equal to zero. This means that, as you experienced, result == number will always be False.
Some redundant parts of your code:
See Splitting integer in Python? to get a list of a number's digits. Most commonly you can just do numbers = [int(i) for i in str(number)]. This will actually solve the problem above as you don't change number this way.
The digits are already integers so no need for an int conversion. It is also more readable to use direct loop in Python rather than looping over indices:
qubes = []
for num in numbers:
qubes.append(num**len(numbers))
sum(i for i in qubes) is just an overly explicit way of saying sum(qubes).
You are printing either "true" or "false" according to a boolean result. There is no need for a condition and you can simply print(result == number).
Putting together all the above, you can achieve this with a single line of code:
print(number == sum(int(digit)**len(str(number)) for digit in str(number)))
This is where you are wrong. you should iterate over the integer not the iterator given by range function
Use this
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
instead of
qubes=[]
for i in range(0,len(numbers)):
c=(int(numbers[i]))**len(numbers)
qubes.append(c)
Also you are referencing the number to itself number=(int(number/10)) so your result value will be 153 but number value will be 0 at the end because you have reduced the value of number. So copy the value of number to another variable (num1 in below code).
Full code:
number=int(input("please enter a number: "))
num1 = number
numbers=[]
while number>0:
rem=number%10
numbers.append(rem)
number=int(number/10)
qubes=[]
for i in numbers:
c=(int(i)**len(numbers))
qubes.append(c)
result = sum(i for i in qubes)
print(result == int(num1))
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Problem: You're a swimmer, and you want to compare all of your race times to find the fastest one. Write a program that continuously takes race times as doubles from standard input, until the input is "no more races," at which point it should print out the time of your fastest race.
The answer I found on another thread was using lists like:
list1 = []
race_time = input("Enter a race time or type no more races to quit: ")
while race_time != "no more races":
list1.append(float(race_time))
race_time = input("Enter a race time or type no more races to quit ")
print(min(list1))
The problem is from if-else, and loops chapter and lists aren't introduced to us yet. How would I store the race times and compare them?
You can just store the best time that you've seen so far and whenever the new time is better overwrite the old one:
import math
best_time = math.inf
[... your code ...]
while ...:
if race_time < best_time:
best_time = race_time
Without list, it will be a little bit difficult to store all races. But as you are only looking for the speedest race:
race_time = input("Enter a race time or type no more races to quit: ")
best_time=float(race_time)
while race_time != "no more races":
race_time = input("Enter a race time or type no more races to quit ")
if race_time != "no more races":
race_time=float(race_time)
if race_time<best_time:
best_time=race_time
print(best_time)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How exactly do I add an additional input to this if function, or atleast add a function which will allow me to give the user another option. Thank you, in advance.
ask = input ("Would you like to 1 input an existing number plate \n or 2 view a random number? 1 or 2: ")
if ask == "1":
print("========================================================================")
ask = input()("Please enter it in such form (XX00XXX): " )
If this ask = input()("Please enter it in such form (XX00XXX): " ) is actually in your code, just changing it to ask = input("Please enter it in such form (XX00XXX): " ) will fix your problem. You had one extra pair of brackets.
DISCLAIMER: This works in Python 3.x
For Python 2, use raw_input("Your question") instead of input("Your question").
As an answer to the question in your own answer:
What is wrong in this code?
ask = input ("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
if int(ask) == 1:
print("========================================================================")
while True:
ask2 = input("Please enter it in such form (XX00XXX): " ).lower()
if re.ask3("[a-z]{2}[0-9]{2}[a-z]{3}",ask2):
print("Verification Success")
break
else:
print("Verification Failed")
You have to indent the while loop once (default is 4 spaces) and everything inside of the while loop twice (default 8 spaces). When pasting a code like this, make sure to include all code needed to run. In this case, show your import re (I had to find out myself you imported that).
I hope I helped.
You are comparing an int(1) to str("1").
It should be
if int(ask) == 1:
# rest of your code
or you can use raw_input() function which returns a string value
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Hey everyone I'm in intro python programming and we're doing out first independent code. The assignment is as follows:
Prompt the user for his or her name. Then prompt the user for two numbers and then perform a mathematical operation of your choice on them. Make sure the program works with decimal numbers, and that you print a full equation in response, not just the result:
Enter a number: 2.3
Enter another number: 3.6
2.3 – 3.6 = -1.3
So I entered:
def main1():
print("This is program 1!")
name = input("Please enter your name: ")
print("Pleased to meet you,", name ,"!") #next line def main2():
print("This is program 2!")
import math
number = input("Enter a number: ")
number = float(number)
numberr = input("Enter another number: ")
numberr = float(numberr)
print = ("number + numberr")
And I keep on getting this:
UnboundLocalError: local variable 'print' referenced before assignment
Help!!
You try to assign a value to print.
You wrote:
print = ("number + numberr")
But you in fact meant:
print(number + numberr)
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I am using Python 3.2 Just so you know what I am doing, here is the assignment:
~The function random.randint from the random module can be used to produce an integer from a range of values. For example, random.randint(1,6) produces the values 1 to 6 with equal probability. A simple tutoring program may randomly select two numbers between 0 and 12 and ask a question such as the following: What is 6 times 8? Upon receiving user response, the computer checks to see if the answer is correct and gives encouraging remarks. Write a program that will loop 10 times producing questions of this form and gives a score for the user at the end.
Here is what I have in my program:
print ("Hello. Let's begin")
for i in range (1,10):
from random import randint
x=randint (0,12)
y=randint (0,12)
print (x,"*" y,"=?")
product= int(input ("What is the product?")
if (product==x*y):
print ("Awesome! That is correct!")
else:
print ("Sorry, that is not correct, but let's try another one!")
I have everything working with all of this. It asks the user a random multiplication question and responds ten times. What I do not understand how to do is to give the user a score at the end. I'm brainstorming ideas and not much is really working. I think I would have to do something like:
score=
But I don't know how to tell the program to calculate the number of correct answers... Do I say score=number of if?
And then when I print the score I can just say:
if (score>5) :
print: ("Great job! You scored a",score,"out of ten!")
else:
print: ("Not the best score, but you can try again! You scored a",score,"out of ten.")
Or is there maybe an easier way to do this?
It seems like it would be simplest to just make a new variable ("score" or suchlike) and initialize it as 0 before the loop. Then, when you check if a user was correct, just increment it by one if it was right, and leave it alone if it was wrong.
Hope this helps!
First, set score to 0
score = 0
then in the loop, try something like
if (product==x*y):
print ("Awesome! That is correct!")
score += 1
else:
print ("Sorry, that is not correct, but let's try another one!")
the important part being the score += 1 this increases the score by one when you get a correct answer. You can the put your score > 5 in after the loop.