def pickOne():
print 'PROPERTIES OF SOLIDS OF REVOLUTION'
print 'Pick a solid to analyze'
print ' 1: ball\n' \
' 2: bwolingPin\n' \
' 3: ellipse\n ' \
' 4: tableLeg\n' \
' 5: quit\n\n '
menu = []
silhouette = ()
flag = 1
while flag:
pickS = raw_input('What is the Number of your choice?')
pickS = int(pickS)
if pickS == 1:
silhouette = str(ball)
flag = 1
if pickS == 2:
silhouette = bowlingPin
flag = 1
if pickS == 3:
silhouette = ellipse
flag = 1
if pickS == 4:
silhouette = tableLeg
flag = 1
if pickS == 5:
flag = 1
main()
else:
flag = 0
print 'Choice %s is not a valid choice' %(pickS)
return
tempinput = raw_input('enter min and max number of points to use (e.g., 2 1000)').split(' ')
minNum = tempinput[0]; maxNum = tempinput[1]
return silhouette , minNum, maxNum
i am new to programming,
i was been told to do a menu for a program, the body code i am done, just this menu really gives me hard time, hope you guys can help me.
I want this fnc work as, if user choose 1-4 for the 1st option, it continues and goes to second Determination that will return two int within 2 to 1000.
the whole function will return the name of the silhouette so that other fnc can call it. and two int.
From my understanding of your question, your logic is flawed. First, you use if statements where you probably want to use elif which is short for else if. Second, your function will always end on printing out 'invalid choice', due to your flag setting. There's also an unused variable and a bunch of unnecessary flag setting, and your minnum and maxnum variables are strings instead of integers (a list comprehension can fix this). You can also do a thing called sequence unpacking to get the values from tempinput. Variable and function names are usually written like lower_case_with_underscores instead of mixedCase.
List comprehensions: https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
Sequence unpacking: https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences
def pick_one():
print '''PROPERTIES OF SOLIDS OF REVOLUTION
Pick a solid to analyse:
1: Ball
2: Bowling Pin
3: Ellipse
4: Table Leg'''
silhouette = None
choice = int(raw_input('Enter the number for your choice: '))
while choice not in [1, 2, 3, 4]:
choice = int(raw_input('Enter the number for your choice: '))
if choice == 1:
silhouette = ball
elif choice == 2:
silhouette = bowling_pin
elif choice == 3:
silhouette = ellipse
elif choice == 4:
silhouette = table_leg
tempinput = raw_input('Enter the minimum and maximum number of points to use (e.g. 2 1000) ').split()
min_num, max_num = [int(n) for n in tempinput]
return silhouette, min_num, max_num
If i understand the question correctly i see a few issues with your code. You are using if when you want to use elif which is short for else if. The way you have it written the "Choice is not valid" option will run everytime unless you set pickS == 5 Here is an updated code.
def pickOne():
print 'PROPERTIES OF SOLIDS OF REVOLUTION'
print 'Pick a solid to analyze'
print ' 1: ball\n' \
' 2: bwolingPin\n' \
' 3: ellipse\n' \
' 4: tableLeg\n' \
' 5: quit\n\n '
menu = []
silhouette = ()
flag = 1
while flag:
pickS = raw_input('What is the Number of your choice? ')
pickS = int(pickS)
if pickS == 1:
silhouette = ball
flag = 1
elif pickS == 2:
silhouette = bowlingPin
flag = 1
elif pickS == 3:
silhouette = ellipse
flag = 1
elif pickS == 4:
silhouette = tableLeg
flag = 1
elif pickS == 5:
flag = 1
main()
else:
flag = 0
print 'Choice %s is not a valid choice' %(pickS)
return
tempinput = raw_input('enter min and max number of points to use (e.g., 2 1000) ').split(' ')
minNum = tempinput[0];
maxNum = tempinput[1]
return silhouette , minNum, maxNum
Related
I have made this simple password generator with the option to choose the length of the password. It seems to randomly add the length to itself however, so if I keep choosing a length of 5 it will occasionally output a password of 10 characters and then go back to 5.
import random
randomnums = []
checker = [0, 0, 0, 0] ##Make sure there are upper, lower case, symbols and numbers.
while True:
length = input("How long do you want your password?: ")
if length.isdigit() == False:
print("please enter a number..\n")
elif int(int(length)) < 4:
print("Please enter a length of 4 or greater...\n")
else:
break
while checker[0] == 0 or checker[1] == 0 or checker[2] == 0 or checker[3] == 0:
for i in range(0,int(length)):
x = random.randrange(0, 4)
if x == 1:
randomnums.append(random.randrange(0, 10))
checker[0] = 1
elif x == 2:
randomnums.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
checker[1] = 1
elif x == 3:
randomnums.append(random.choice('ABCDEFGHIJKLMNPQRSTUVWXYZ'))
checker[2] = 1
else:
randomnums.append(random.choice('!##$%^&*()_+:"}|<>?'))
checker[3] = 1
password = ''.join(map(str, randomnums)) ##join list to string
print(password)`
You could get any multiple of length with this code. It adds length characters in the body until you got the required length. You should instead generate a password and check it, and if it is bad, repeat.
I am using python3 and I have this code where I ask the user for three inputs. then I perform a calculation on them. I would like to keep adding the calculation results to a list. How to do that?
...
if choice == '1': #my fist input x
while True:
x = int(input('Please insert the number of things you consider yourself a fan of'))
if x > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '2': #my second input y
while True:
y = int(input('Please insert the number of hobbies you like to do every month'))
if y % 4 == 0:
break
else:
print('Please insert a valid number')
elif choice == '3': #my third input z
while True:
z = int(input('Please insert the number of sports you like'))
if z > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '4': #the calculation part
import math
def square_root():
c=(42 * y ** 2)/(z + 1)
nerd_score=int(x*math.sqrt(c))
return nerd_score
print('your nerd score is', square_root())
I want the loop to keep going, and each result to be added to the list. until the user exits the loop.
In my understanding, there are two problems you want to solve:
loop keep going, util user want to exit the loop
add every result to a list
Sample code is here:
def loop_calculation(choice):
# record results in list
results = []
# loop keep going, util user input choice 'x' which means exit
while choice != 'x':
if choice == '1': # my fist input x
while True:
x = int(input('Please insert the number of things you consider yourself a fan of'))
if x > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '2': # my second input y
while True:
y = int(input('Please insert the number of hobbies you like to do every month'))
if y % 4 == 0:
break
else:
print('Please insert a valid number')
elif choice == '3': # my third input z
while True:
z = int(input('Please insert the number of sports you like'))
if z > 0:
break
else:
print('Please insert a number higher than 0')
elif choice == '4': # the calculation part
import math
def square_root():
c = (42 * y ** 2) / (z + 1)
nerd_score = int(x * math.sqrt(c))
return nerd_score
result = square_root()
print('your nerd score is', result)
# add each result to list
results.append(result)
return results
Hope it will help you.
I am trying to write a conditional where if a ends in 1 then it will answer with "st root" unless it ends with an 11 so it will be like 1st root or 11th root
(Then also work in similar ways for 2/12 and 3/13)
Here is the code I have tried
def n():
print("Only enter whole numbers\n ")
base = float(input("Enter number to take the root of, then hit enter:\n "))
input_string = input("Enter degree of roots (if more than one, separate by space) then hit enter:\n ")
list = input_string.split()
a = 1
for num in list:
base **= (1/float(num))
for num in list:
a *= int(num)
if str(a)[-1] == '1':
if str(a)[-1] != '11':
print(a,"st root",base)
elif str(a)[-1] == '2':
if str(a)[-1] != '12':
print(a,"nd root",base)
elif str(a)[-1] == '3':
if str(a)[-1] != '13':
print(a,"rd root",base)
else:
print(a,"th root",base)
n()
You can almost translate your sentence directly into code:
if lastCharacter is 1 and not penUltimateCharacter is 1
so:
if (str(a)[-1] == '1' and str(a)[-2] != '1'):
print(a,"st root",base)
I found this answer for converting integers to ordinal numbers.
https://codereview.stackexchange.com/questions/41298/producing-ordinal-numbers
Here is the final code snippet
# much code can be improved by using a datastructe.
SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
def ordinal(num):
# I'm checking for 10-20 because those are the digits that
# don't follow the normal counting scheme.
if 10 <= num % 100 <= 20:
suffix = 'th'
else:
# the second parameter is a default.
suffix = SUFFIXES.get(num % 10, 'th')
return str(num) + suffix
What you essentially need is the last digit and the last two digits as a number:
a = 1234 #My number to check
last_digit = a - int(a/10)*10
two_two_last_digits = a - int(a/100)*100
Now, these two numbers have the nice relationship, that they difference is 10 whenever your connection is met, so you have:
if (two_last_digits - last_digit) != 10:
...
So with the 'unless' part covered, the if part can be expressed using a dict:
cases = {1: "st root ", 2:"nd root", 3:"rd root"}
Taking all things together we get:
if (two_last_digits - last_digit) != 10:
print(a, "th root", base)
else:
try:
print(a, cases[last_digit], base)
except KeyError:
print(a, "th root", base)
i have no idea why this is broken. Also dont tell me to use python's built in function because this is designed for some practice not to actually be used. It is binary to decimal that is broken. It has a index error with the variable 'index'
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu
this doesn't seem right
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
you never enter this loop, do you?
a better loop would be something like
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
also, since you're just practicing, you should find a better way to jump from menu to functions and back. you're doing recursive calls, which is a waste of stack, i.e. your functions actually never finish but just call more and more functions.
Some fixes:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION
I am coding a program that lets you type in the three angles or sides of a triangle, and it tells if it's equilateral, isosceles etc. I am not worrying about the rest for now, but I'm stuck on the equilateral part of it. Here is my code:
def idtri():
print("\nDo you have all three sides, or al three angles?")
print("(1) Sides")
print("(2) Angles")
choice = input()
if choice == 1:
print("\nType in the lengths of all of the sides.")
t1 = input("1: ")
t2 = input("2: ")
t3 = input("3: ")
print("Your triangle is an equalateral triangle.")
menu()
elif choice == 2:
pass
idtri()
The first thing to note is that, for identifying the triangle as scalene, isoceles, or equilateral, it doesn't matter whether the three values you have are the angles or the side lengths, the process is:
If all three values are the same, the triangle is equilateral;
otherwise, if any two values are the same, the triangle is isoceles;
otherwise, the triangle is scalene.
So you can write a simple function to return the type based on the number of equal values provided:
id_triangle = lambda a, b, c: {0: 'scalene', 1: 'isoceles', 3: 'equilateral'}\
[(a == b) + (a == c) + (b == c)]
and then call that from your interactive script, like:
print('Your triangle is %s.' % id_triangle(t1, t2, t3))
You can also use the counter from the Python collections:
from collections import Counter
def idtri():
cnt = Counter()
side1 = input('Enter length of first side: ')
cnt[side1] += 1
side2 = input('Enter length of second side: ')
cnt[side2] += 1
side3 = input('Enter length of third side: ')
cnt[side3] += 1
if 3 in cnt.values():
print('Equilateral Triangle')
elif 2 in cnt.values():
print('Isosceles Triangle')
else:
print('Scalene Triangle')
if __name__ == "__main__":
idtri()