[英]I'm trying to make a user input dictionary for extra credit in my class and I can't figure out how to properly end the program
[英]I need to figure out how to make my program repeat. (Python coding class)
我是python编码课程的初学者。 我已完成大部分工作,并且程序本身可以运行,但是我需要找出一种方法使程序询问是否要减去或增加问题,以及用户是否想要其他问题。 我向我的老师寻求帮助,他没有回过头,所以我只是想弄明白我到底需要做什么。
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
您将需要执行以下操作:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
我已经看到这种构造(即使用break
)比在Python中使用哨兵使用的频率更高,但是任何一种都可以。 前哨版本如下所示:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
您还需要在代码中进行比我更多的错误检查。
要求用户输入很简单,您只需要使用python内置的input()函数即可。 然后,您将存储的答案与某些可能的结果进行比较。 在您的情况下,这可以正常工作:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
重复代码While
您可以选择循环,但是当起始条件为true时,它们将在其中重复执行一条语句。
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
使用input()
函数的结果始终是一个字符串。 我们在其上使用.upper()
方法,将其转换为大写。 如果您这样写,那么有人回答N还是n都没关系,循环仍然会终止。
如果您想再问一个问题,请使用while循环,然后要求用户输入。 如果您希望用户输入是否要加法或减法,则您已经使用该工具来要求输入。 只是问用户一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.