即使在python中初始化变量不是必要的,我的教授仍然希望我们为实践做这件事.我写了我的程序,它工作正常,但在我尝试初始化一些变量后,当我尝试运行它时,我收到了一条错误消息.这是我的计划的第一部分:
def main():
grade_1, grade_2, grade_3, average = 0.0
year = 0
fName, lName, ID, converted_ID = ""
infile = open("studentinfo.txt", "r")
data = infile.read()
fName, lName, ID, year = data.split(",")
year = int(year)
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
# Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
grade_1, grade_2, grade_3 = …Run Code Online (Sandbox Code Playgroud) 我有一个名单,我希望我的程序随机选择其中一个名称.我尝试使用以下内容:
import random
def main():
Arkansas = 1
Manchuria = 2
Bengal = "3"
Baja_California = 4
Tibet = 5
Indonesia = 6
Cascade_Range = 7
Hudson_Bay = 8
High_Plains = 9
map = random.randrange(1, 10)
print(map)
main()
Run Code Online (Sandbox Code Playgroud)
我也尝试使用eval()函数for 将每个数字作为字符串randrange(),但没有一个工作.
我在shell中尝试了以下内容
infile = open("studentinfo.txt", "r")
infile.read()
Run Code Online (Sandbox Code Playgroud)
它返回文件中的文本,这是我想要它做的.但是,当我写它并将其保存为程序时
def main():
infile = open("studentinfo.txt", "r")
infile.read()
main()
Run Code Online (Sandbox Code Playgroud)
它只是返回空行.
我试图右键单击该文件并重命名它,但它甚至不会向我显示扩展名,因此我可以将其删除。我也试过去属性,我也不能从那里做。我没有直接用 python 的 Tkinter 编码,我使用了我的书附带的定制图形库。
这是我的问题的简化版本
def findX():
x = 2
return x
def main():
y = findX()
y = y + 10
#(unknown code here)
print (y)
main()
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
2
Run Code Online (Sandbox Code Playgroud)
我可以在不减去10或没有再次运行findX()的情况下执行此操作吗?我认为将y = findX()定义为全局变量可能有效,但我想尽可能避免使用全局变量.
python随机生成器被认为是"好"吗?如同,它是否很好地模拟随机性?我制作了一个小程序,模拟一个人从(0,0)开始,并在东,西,北,南随机步骤.当您运行具有越来越多步骤的模拟时,您会期望人的最终位置越来越接近原点.但是,当我增加模拟中的步数时,最终位置越来越远离原点.我使用的程序在这里:
import random
def walk():
north = 0
east = 0
for i in range(10000):
direction = random.randint(0, 100)
if direction <= 25:
north = north + 1
elif direction > 25 and direction <= 50:
north = north - 1
elif direction > 50 and direction <= 75:
east = east + 1
else:
east = east - 1
return north, east
def main():
for i in range(500):
north, east = walk()
print("NE : ", north, east)
main()
Run Code Online (Sandbox Code Playgroud) 如果你有一个这样的程序,例如:
print("Hi there \n")
print("Hello")
Run Code Online (Sandbox Code Playgroud)
这个程序会被认为有2行或3行输出吗?我知道空白行并不是什么东西,但它仍然是程序所做的事情.