Program not running with error unsupported operand type(s) for +: 'function' and 'int' - python-3.7

Im creating a program for NIM for my Python Intro class, and am having a problem with trying to get the program to finish.
I am at a loss...
def main():
import random
#User random to generate integer between 10 and 100 for random pile size of marbles.
ballCount = random.randint(10, 100)
print("The size of the pile is: ",ballCount)
#Generate a random integer between 0 and 1, this will tell if the human or computer takes first turn.
def playerTurn(ballCount):
playerTurn = random.randint(0, 1)
if playerTurn == 0:
print("Its the computers turn...")
else:
print("Its your turn...")
#Generate a random integer between 0 and 1, to determine if the computer is smart or dumb.
computerMode = random.randint(0, 1)
def computerDumbMode(ballCount):
computerMode = random.randint(0, 1)
if computerMode == 0:
print("This computer is very dumb, no need to stress")
def computerSmartMode(ballCount):
computerMode = random.randint(0, 1)
if computerMode == 1:
print("This computer is very intelligent, beware")
#In dumb mode the computer generates random values (between 1 and n/2),
#you will use a random integer n for ballCount, when it is the computers turn.
while ballCount != 1: #This will compile untill you are left with only one marble.
if playerTurn == 0: #This will initiate computers turn.
if computerMode == 1: #This will initiate Smart Mode.
temp = random.randint(1, ballCount/2) #Pick a random number between 1, and n/2.
else: # Pick your own number of Marbles for your ballCount (n).
if ballCount - 3 > 0 and ballCount - 3 < ballCount/2:
temp = ballCount - 3
elif ballCount - 7 > 0 and ballCount - 7 < ballCount/2:
temp = ballCount - 7
elif ballCount - 15 > 0 and ballCount - 15 < ballCount/2:
temp = ballCount - 15
elif ballCount - 31 > 0 and ballCount - 31 < ballCount / 2:
temp = ballCount - 31
else:
temp = ballCount - 63
print("The computer has chosen: %d marbles." % temp) #Print the number of marbles the computer has chosen.
ballCount -= temp #Then subtract the number of marbles chosen by the computer.
else:
ballCountToPick = int(input("It is now your turn, Please pick the number of marbles in the range 1 - %d: " % int(ballCount/2))) #Reads the number of marbles to be picked by user.
while ballCountToPick < 1 or ballCountToPick > ballCount/2: #If computer reads this invalidly, it will try repeatedly.
ballCountToPick = int(input("The number you chose, is incorrect. Try again, and pick marbles in the range 1 - %d: " % int(ballCount/2)))
ballCount -= ballCountToPick #Subtract the marbles that were chosen by user.
playerTurn = (playerTurn + 1) % 2 #Changes the turn of player.
print("Now the pile is of size %d." % ballCount)
if playerTurn == 0: #Show the outcome.
print("You came, you saw, and you won... CONGRATULATIONS!!!")
else:
print("Once again... You lost and the computer wins!!!")
main()
Trying to get the program/game to run and print end result if the computer or person wins!

Your "playerTurn" variable is a function in the following line:
playerTurn = (playerTurn + 1) % 2 #Changes the turn of player.
Have a separate "playerTurn" function and "player_turn" variable will resolve your problem.

Related

dht11 sensor only retuning unexpected number of pulse often

I am trying to make a simple water pump controller using a dth11 to make the pump turn on more frequently when the temperature is higher. i have it working but every 4th or 5th time i call measure on the dht11 sensor i get an error saying "InvalidPulseCount: Expected 82 but got 0 pulses" or "InvalidPulseCount: Got more than 82 pulses". I have added try block that is stopping the program from crashing but would really like to figure out why it is happening. I also had to edit the dht.py lib to have 82 instead of 84 as the default expected pulses because that was what was commonly returned.
here is my main.py file
from machine import Pin
from time import sleep_ms
import dht
import I2C_LCD_driver
sensor = dht.DHT11(Pin(28))
lcd = I2C_LCD_driver.lcd()
pump = Pin(7, machine.Pin.OUT)
counter = 0
pumpTime = 30
normalTime = 60
hotTime = 30
lowTemp = 19
# sensor variables only updated every 3 loops
lastMesure = 1
temp = 0
humid = 0
first = True
while True:
# sensor.messure can only be called ever 3 seconds
# start at 1 and set to zero in the first loop for our first messurement
lastMesure += -1
if lastMesure <= 0:
try:
sensor.measure()
lastMesure = 3
temp = round((sensor.temperature), 0)
humid = sensor.humidity
except:
print("something went wrong")
print("Counter: {:.0f} pumpping:{:0.f}".format(counter, pump.value()))
print("Temp: {:.0f}℃ HUMIDITY: {:.0F}% ".format(temp, humid))
# if the pump is running
if pump.value() == 1:
if counter >= pumpTime: # if it has been the set pump run time
pump.value(0) # turn off pump
counter = 0 # reset counter
else:
counter += 1
else:
# check current temp
# if warmer then {lowTemp} check for {hotTime} else check for {normalTime}
if (temp > lowTemp and counter >= hotTime) or counter >= normalTime:
pump.value(1) # turn on pump
counter = 0 # reset counter
else:
counter += 1
# print current data to the screen
lcd.lcd_clear()
lcd.lcd_display_string("T: {:.0f}C H:{:.0f}%".format(temp, humid), 1)
if pump.value() == 1:
status = f'Pumping {pumpTime - counter}s'
lcd.lcd_display_string(status, 2);
else:
lcd.lcd_display_string("Pump off ", 2)
sleep_ms(1000)
here is a picture of my breadboard set up. I have run it both with and without a 1k pull up resistor on the data pin

python code worked with Proxy server, now not working without

'All,this is code that will put production counts off machines and load them into a lean manufacturing software. This tracks production states and Preventative maintenance for machines. The code used to work until network changes started with changing v-lans and now the latest no proxy server. since then they assigned the PC which this code will be running on with a static IP not requiring it to read from the company server, nor go through a proxy. When starting Python with command line Shift right click (l2l.py) the screen is black then goes away. If the code is tested with Notepad++, the code gives errors pertaining to xlrd, then requests. I changed all upgraded the xlrd and the files are in the script folder of the pc. Still striking out to no avail. I don't do much C code, but have been searching several websites for answers. Any help would be appreciated. Thank You- Bruno'
import xlrd # module to interface with excel
import requests # module to upload the data to L2L
from datetime import datetime #module for time stamps
import os
import time
outtime = 5
import requests
session = requests.Session()
session.trust_env = false
response = session.get('http://www.graham.leading2lean.com')
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
L1Startlog = 0
L1Startgood = 0
L1Flog = 0
L1Fgood = 0
L1EndLog = 0
L1EndGood = 0
L1Err = 0
file_location = "C:/Users/brfdc/Desktop/L2L.xlsm" #location of excel file on local computer
workbook = xlrd.open_workbook(file_location)#opening the excel file specified in the previous line
sheet = workbook.sheet_by_index(0) #opening the first sheet in the excel file.
L3Sgood = sheet.cell_value(3,1) #Line 3 starting report good bottle count
#--------------------------------------------------
#Line three error checking
if (L3Sgood != 42) and (L3Slog != 42):
L3Startgood = L3Sgood
L3Startlog = L3Slog
else:
pass
if (L3Bottle != 42):
L3BottleG = L3Bottle
else:
L3BottleG = 0
#end of line 3 error checking
#--------------------------------------------------
if (L5Sgood != 42) and (L5Slog != 42): #Line 5 Error checking
L5Startgood = L5Sgood #Line 5
L5Startlog = L5Slog #Line 5
else:
pass
if (L1Sgood !=42) and (L1Slog != 42): #Line 1 Error checking
L1Startgood = L1Sgood #Line 1
L1Startlog = L1Slog #Line 1
else:
pass
if (L2Sgood != 42) and (L2Slog != 42): #Line 2 Error checking
L2Startgood = L2Sgood #Line 2
L2Startlog = L2Slog #Line 2
else:
pass
if (L7Sgood != 42) and (L7SAlog != 42) and (L7SBlog != 42): #Line 7 Error checking
L7Startgood = L7Sgood #Line 7
L7StartlogA = L7SAlog #Line 7
L7StartlogB = L7SBlog #Line 7
else:
pass
if (L6Sgood != 42) and (L6Slog != 42): #Line 6 error checking
L6Startgood = L6Sgood #Line 6
L6Startlog = L6Slog #Line 6
else:
pass
if (L8Sgood != 42) and (L8SAlog != 42) and (L8SBlog != 42): #Line 8 Error checking
L8Startgood = L8Sgood #Line 8
L8StartlogA = L8SAlog #Line 8
L8StartlogB = L8SBlog #Line 8
else:
pass
Api_End_Point = 'https://graham.leading2lean.com/api/1.0/pitchdetails/record_details/'
API_key = "c74de26eee9d5617de3218b5301d00de"
url = Api_End_Point +"?auth=" + API_key
DATETIME_SECONDS_STRING_FORMAT = "%Y-%m-%d %H:%M:%S"
testsendfinal = 0
L7StartlogT = L7StartlogA + L7StartlogB #Add the two SIPA sides together Line 7
L8StartlogT = L8StartlogA + L8StartlogB #Add the two SIPA sides together Line 8
while True:
#while True:
try:
startingTime = datetime.now().strftime(DATETIME_SECONDS_STRING_FORMAT) #assigning the current time to this variable
print(startingTime)
secs = datetime.now().strftime("%S")
mins = datetime.now().strftime("%M")
#corrective math for on the dot 30 minute marks because program drifts in time over the course of an hour.
if (int(mins) >= 27 and int(mins) < 30):
minutes_to_30 = 29 - int(mins)
minutes_to_seconds = minutes_to_30 * 60
secs_to_go = 60 - int(secs)
seconds_to_30 = secs_to_go + minutes_to_seconds
pause_time = seconds_to_30
print(seconds_to_30)
else:
pause_time = 60 #180
#--------------------------------------------------------------------------------------------------------------------------
print('start time of log ' + startingTime) #this is just printing on the screen what the time is. used for troubleshooting
L3SLoss = L3Startlog - L3Startgood #Line 3 Difference in two counters to calculate scrap
L5SLoss = L5Startlog - L5Startgood #Line 5 Difference in two counters to calculate scrap
L1SLoss = L1Startlog - L1Startgood #Line 1 Difference in two counters to calculate scrap
L2SLoss = L2Startlog - L2Startgood #Line 2 Difference in two counters to calculate scrap
L6SLoss = L6Startlog - L6Startgood #Line 6 Difference in two counters to calculate scrap
L7SLoss = L7StartlogT - L7Startgood #Line 7 Difference in two counters to calculate scrap
L8SLoss = L8StartlogT - L8Startgood #Line 8 Difference in two counters to calculate scrap
#change 6:30 and 18:30 start of report numbers. force these numbers to zero when at these two times.
hour_time = datetime.now().strftime("%H")
minute_time = datetime.now().strftime("%M")
if int(hour_time) == 6 or int(hour_time) == 18:
if int(minute_time) == 30:
L1SLoss = 0
L2SLoss = 0
L3SLoss = 0
L5SLoss = 0
L6SLoss = 0
L7SLoss = 0
L8SLoss = 0
L1Startgood = 0
L2Startgood = 0
L3Startgood = 0
L5Startgood = 0
L6Startgood = 0
L7Startgood = 0
L8Startgood = 0
L1EndGood = 0#added this 10/29/2018
L2EndGood = 0
L3EndGood = 0
L5EndGood = 0
L6EndGood = 0
L7EndGood = 0
L8EndGood = 0
L1EndLog = 0
L2EndLog = 0
L3EndLog = 0
L5EndLog = 0
L6EndLog = 0
L7EndLogA = 0
L7EndLogB = 0
L8EndLogA = 0
L8EndLogB = 0
os.system("new.bat")
else:
print("Not right minute for number force to zero")
else:
print("Not Right time for number force to zero ")
#--------------------------------------------------------------------------------------
time.sleep(pause_time) # sleep for ~3 minutes
#--------------------------------------------------------------------------------------
currentTime = datetime.now().strftime(DATETIME_SECONDS_STRING_FORMAT) #assigning the current time to this variable.
file_location = "C:/Users/brfdc/Desktop/L2L.xlsm" #location of excel file on local computer
workbook = xlrd.open_workbook(file_location) #opening the excel file specified in the previous line
sheet = workbook.sheet_by_index(0) #opening the first sheet in the excel file
L3Fgood = sheet.cell_value(3,1) #Line 3 end report good bottle count
L3Flog = sheet.cell_value(2,1) #Line 3 end report log bottle count
L5Flog = sheet.cell_value(6,1) #Line 5 end report log bottle count
L5Fgood = sheet.cell_value(7,1) #Line 5 end report good bottle count
L1Flog = sheet.cell_value(9,2) #Line 1 end report log bottle count
L1Fgood = sheet.cell_value(10,1)#Line 1 end report good bottle count
L2Fgood = sheet.cell_value(14,1)#Line 2 end report good bottle count
L2Flog = sheet.cell_value(13,1) #Line 2 end report log bottle count
L7Fgood = sheet.cell_value(21,1)#Line 7 starting report good bottle count
L7FAlog = sheet.cell_value(19,1)#Line 7 starting report log bottle count side A
L7FBlog = sheet.cell_value(20,1)#Line 7 starting report log bottle count side B
L6Flog = sheet.cell_value(17,1) #Line 6 end report log bottle count
L6Fgood = sheet.cell_value(18,1)#Line 6 end report good bottle count
L3Bottle = sheet.cell_value(3,3)#Line 3 bottle being run. 1 means running arizona
L8Fgood = sheet.cell_value(25,1)#Line 8 starting report good bottle count
L8FAlog = sheet.cell_value(23,1)#Line 8 starting report log bottle count side A
L8FBlog = sheet.cell_value(24,1)#Line 8 starting report log bottle count side B
mins_time = datetime.now().strftime("%M")
m = datetime.now().strftime("%M")
if (L3Fgood != 42) and (L3Flog != 42): #Line 3
L3EndGood = L3Fgood #Line 3
L3EndLog = L3Flog #Line 3
L3Err = 0
else:
L3Err += 1
if (L3Bottle != 42):
L3BottleG = L3Bottle
if (L5Flog != 42) and (L5Fgood != 42): #Line 5
L5EndGood = L5Fgood #Line 5
L5EndLog = L5Flog #Line 5
L5Err = 0
else:
L5Err += 1
if (L1Flog != 42) and (L1Fgood != 42): #Line 1
L1EndGood = L1Fgood #Line 1
L1EndLog = L1Flog #Line 1
L1Err = 0
else:
L1Err += 1
if (L2Fgood != 42) and (L2Flog != 42): #Line 2
L2EndGood = L2Fgood #Line 2
L2EndLog = L2Flog #Line 2
L2Err = 0
else:
L2Err += 1
if (L7Fgood != 42) and (L7FAlog != 42) and (L7FBlog != 42):
L7EndGood = L7Fgood
L7EndLogA = L7FAlog
L7EndLogB = L7FBlog
L7Err = 0
else:
L7Err += 1
if (L6Fgood != 42) and (L6Flog != 42):
L6EndGood = L6Fgood
L6EndLog = L6Flog
L6Err = 0
else:
L6Err += 1
if (L8Fgood != 42) and (L8FAlog != 42) and (L8FBlog != 42):
L8EndGood = L8Fgood
L8EndLogA = L8FAlog
L8EndLogB = L8FBlog
L8Err = 0
else:
L8Err += 1
L3EndLoss = L3EndLog - L3EndGood #Line 3 Difference in two counters at end of report to calculate scrap
L5EndLoss = L5EndLog - L5EndGood #Line 5 Difference in two counters at end of report to calculate scrap
L1EndLoss = L1EndLog - L1EndGood #Line 1 Difference in two counters at end of report to calculate scrap
L2EndLoss = L2EndLog - L2EndGood #Line 2 Difference in two counters at end of report to calculate scrap
L6EndLoss = L6EndLog - L6EndGood #Line 6 Difference in two counters at end of report to calculate scrap
L7EndLogT = L7EndLogA + L7EndLogB #Line 7 add two SIPA log bottle sides together
L7EndLoss = L7EndLogT - L7EndGood #Line 7 Difference in two counters at end of report to calculate scrap
L8EndLogT = L8EndLogA + L8EndLogB #Line 8 add two SIPA log bottle sides together
L8EndLoss = L8EndLogT - L8EndGood #Line 8 Difference in two counters at end of report to calculate scrap
#--------------------------------------------------------------------------------------
L3ChangeGood = L3EndGood - L3Startgood #Line 3 Change in starting report good bottle count and ending report good bottle count
L3ChangeLoss = L3EndLoss - L3SLoss #Line 3 Change in two different scrap numbers calculated above
L5ChangeGood = L5EndGood - L5Startgood #Line 5 Change in starting report good bottle count and ending report good bottle count
L5ChangeLoss = L5EndLoss - L5SLoss #Line 5 Change in starting report loss calculation and ending report loss calculation
L1ChangeGood = L1EndGood - L1Startgood #Line 1 Change in starting report good bottle count and ending report good bottle count
L1ChangeLoss = L1EndLoss - L1SLoss #Line 1 Change in starting report loss calculation and ending report loss calculation
L2ChangeGood = L2EndGood - L2Startgood #Line 2 Change in starting report good bottle count and ending report good bottle count
L2ChangeLoss = L2EndLoss - L2SLoss #Line 2 Change in two different scrap numbers calculated above
L6ChangeGood = L6EndGood - L6Startgood #Line 6 change in starting report good bottle count and end report good bottle count
L6ChangeLoss = L6EndLoss - L6SLoss #Line 6 change in two different scrap numbers calculated above
L7ChangeGood = L7EndGood - L7Startgood #Line 7 Change in starting report good bottle count and ending report good bottle count
L7ChangeLoss = L7EndLoss - L7SLoss #Line 7 Change in two different scrap numbers calculated above
L8ChangeGood = L8EndGood - L8Startgood #Line 8 Change in starting report good bottle count and ending report good bottle count
L8ChangeLoss = L8EndLoss - L8SLoss #Line 8 Change in two different scrap numbers calculated above
#--------------------------------------------------------------------------------------
L7DiffLogA = L7EndLogA - L7StartlogA
L7DiffLogB = L7EndLogB - L7StartlogB
L8DiffLogA = L8EndLogA - L8StartlogA
L8DiffLogB = L8EndLogB - L8StartlogB
if L7DiffLogA >= 1 and L7DiffLogB == 0:
L7Bottle = "Side A"
elif L7DiffLogB >= 1 and L7DiffLogA == 0:
L7Bottle = "Side B"
else:
L7Bottle = "Side A & B"
if L8DiffLogA >= 1 and L8DiffLogB == 0:
L8Bottle = "Side A"
elif L8DiffLogB >= 1 and L8DiffLogA == 0:
L8Bottle = "Side B"
else:
L8Bottle = "Side A & B"
#--------------------------------------------------------------------------------------
#below is logic to never send negative numbers for actual bottles and not send a relatively large amount of lost bottles
m = datetime.now().strftime("%M")
if (L3ChangeLoss < -1000) or (L3ChangeLoss>300): #Line 3
L3SendLoss = 0 #Line 3
else: #Line 3
L3SendLoss = L3ChangeLoss #Line 3
if (L3ChangeGood <0): #Line 3
if int(m) < 33 and int(m) > 30: #Line 3
L3SendGood = L3EndGood #Line 3
else: #Line 3
L3SendGood = 0 #Line 3
else: #Line 3
L3SendGood = L3ChangeGood #Line 3
if (L5ChangeLoss < -1000) or (L5ChangeLoss>600): #Line 5
L5SendLoss = 0 #Line 5
else: #Line 5
L5SendLoss = L5ChangeLoss #Line 5
if (L5ChangeGood < 0): #Line 5
if int(m) < 33 and int(m) > 30: #Line 5
L5SendGood = L5EndGood #Line 5
else: #Line 5
L5SendGood = 0 #Line 5
else: #Line 5
L5SendGood = L5ChangeGood #Line 5
if (L1ChangeLoss < -1000): #Line 1
L1SendLoss = 0 #Line 1
else: #Line 1
L1SendLoss = L1ChangeLoss #Line 1
if (L1ChangeGood < 0): #Line 1
if int(m) < 33 and int(m) > 30: #Line 1
L1SendGood = L1EndGood #Line 1
else: #Line 1
L1SendGood = 0 #Line 1
else: #Line 1
L1SendGood = L1ChangeGood #Line 1
if (L2ChangeLoss < -1000) or (L2ChangeLoss>300): #Line 2
L2SendLoss = 0 #Line 2
else: #Line 2
L2SendLoss = L2ChangeLoss #Line 2
if (L2ChangeGood <0): #Line 2
if int(m) < 33 and int(m) > 30: #Line 2
L2SendGood = L2EndGood #Line 2
else: #Line 2
L2SendGood = 0 #Line 2
else: #Line 2
L2SendGood = L2ChangeGood #Line 2
if (L6ChangeLoss<-1000) or (L6ChangeLoss>3000): #Line 6
L6SendLoss = 0 #Line 6
else: #Line 6
L6SendLoss = L6ChangeLoss #Line 6
if (L6ChangeGood <0): #Line 6
if int(m) < 33 and int(m) > 30: #Line 6
L6SendGood = L6EndGood #Line 6
else: #Line 6
L6SendGood = 0 #Line 6
else: #Line 6
L6SendGood = L6ChangeGood #Line 6
if (L7ChangeGood <0): #Line 7
if int(m) < 33 and int(m) > 30: #Line 7
L7SendGood = L7EndGood #Line 7
else: #Line 7
L7SendGood = 0 #Line 7
else: #Line 7
L7SendGood = L7ChangeGood #Line 7
if (L8ChangeGood <0): #Line 8
if int(m) < 33 and int(m) > 30: #Line 8
L8SendGood = L8EndGood #Line 8
else: #Line 8
L8SendGood = 0 #Line 8
else: #Line 8
L8SendGood = L8ChangeGood #Line 8
if (L3BottleG == 0):
RunningBottle = "Heinz"
elif (L3BottleG == 2):
RunningBottle = "Hershey"
elif (L3BottleG == 3):
RunningBottle = "RedGold"
else:
RunningBottle = "128oz Arizona"
print(L3BottleG,RunningBottle)
#--------------------------------------------------------------------------------------
parameters = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0003', # line code for line 3
'start': startingTime, # start time of data being collected
'end': currentTime, # end time of data being collected
'actual': L3SendGood, # number of good bottles going to
'scrap': L3SendLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 2, # number of operators on the line. usually one but have to ask if this is needed
'productcode': RunningBottle, # this will be where we put the name of product being produced. if needed.128oz Arizona Heinz
}
parametersL5 = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0005', # line code for line 5
'start': startingTime, # start time of data being collected
'end': currentTime, # end time of data being collected
'actual': L5SendGood, # number of good bottles going to
'scrap': L5SendLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 1, # number of operators on the line. usually one but have to ask if this is needed
'productcode': 'Bottle', # this will be where we put the name of product being produced. if needed.
}
parametersL1 = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0001', # line code for line 1
'start': startingTime, # start time of data being collected
'end': currentTime, # end time of data being collected
'actual': L1SendGood, # number of good bottles going to
'scrap': L1SendLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 1, # number of operators on the line. usually one but have to ask if this is needed
'productcode': 'Old Country', # this will be where we put the name of product being produced. if needed.
}
parametersL2 = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0002', # line code for line 2
'start': startingTime, # start time of data being collected
'end': currentTime, # end time of data being collected
'actual': L2SendGood, # number of good bottles going to
'scrap': L2SendLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 1, # number of operators on the line. usually one but have to ask if this is needed
'productcode': '128oz Arizona', # this will be where we put the name of product being produced. if needed.
}
parametersL7 = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0007', # line code for line 7
'start': startingTime, # start time of data being collected
'end': currentTime, # end time of data being collected
'actual': L7SendGood, # number of good bottles going to
'scrap': L7ChangeLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 1, # number of operators on the line. usually one but have to ask if this is needed
'productcode': L7Bottle, # this will be where we put the name of product being produced. if needed.
}
parametersL8 = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0008', # line code for line 7
'start': startingTime, # start time of data being collected
'end': currentTime, # end time of data being collected
'actual': L8SendGood, # number of good bottles going to
'scrap': L8ChangeLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 1, # number of operators on the line. usually one but have to ask if this is needed
'productcode': L8Bottle, # this will be where we put the name of product being produced. if needed.
}
parametersL6 = {
'site': 1, # the site code for site 0123 (bradford) is 1
'linecode': '0123-BLWM-0006', # line code for line 7
'start': 'startingTime', # start time of data being collected
'end': 'currentTime', # end time of data being collected
'actual': L6SendGood, # number of good bottles going to
'scrap': L6ChangeLoss, # This will be determined as to what numbers i really need. I assume log count less final count.
'operation_count': 1, # number of operators on the line. usually one but have to ask if this is needed
'productcode': "L6Bottle", # this will be where we put the name of product being produced. if needed.
}
if (L3SendGood == 0) and (L3SendLoss == 0):
print("Zero numbers no Send Line 3") #This is just for my entertainment
else:
print("sending L3")
three = requests.post(url, proxies=proxies, data=parameters,verify=False,timeout=out-time) #line actually making the call to upload the log
#print(three)
L3list = three.text
if L3list.find("true") != -1:
L3Startgood = L3EndGood #RT is running total. this will be for bottle count correction
L3Startlog = L3EndLog
print("L3 good")
else:
print("Number didn-t go through. Will not update starting numbers.")
if (L5SendGood == 0) and (L5SendLoss == 0):
print("Zero numbers no Send Line 5")
else:
print("sending L5")
five = requests.post(url, data=parametersL5,verify=False,timeout=out-time)
#print(five)
L5list = five.text
if L5list.find("true") != -1:
L5Startgood = L5EndGood
L5Startlog = L5EndLog
print("L5 good")
else:
Print("L5 numbers didn't go through. Will not update starting numbers.")
if (L1SendGood == 0) and (L1SendLoss == 0):
print("Zero numbers no Send Line 1")
else:
print("sending L1")
one = requests.post(url, data=parametersL1,verify=False,timeout=out-time)
#print(one)
L1list = one.text
if L1list.find("true") != -1:
L1Startgood = L1EndGood
L1Startlog = L1EndLog
print("L1 good")
else:
print("L1 numbers didn't go through. Will not update starting numbers.")
if (L2SendGood == 0) and (L2SendLoss == 0):
print("Zero numbers no Send Line 2")
else:
print("sending L2")
two = requests.post(url, data=parametersL2,verify=False,timeout=out-time)
#print(two)
L2list = two.text
if L2list.find("true") != -1:
L2Startgood = L2EndGood
L2Startlog = L2EndLog
print("L2 good")
else:
print("L2 numbers didn't go through. Will not update starting numbers.")
if (L7SendGood == 0) and (L7ChangeLoss == 0):
print("Zero numbers no Send Line 7")
else:
print("sending L7")
seven = requests.post(url, data=parametersL7,verify=False,timeout=out-time)
#print(seven)
L7list = seven.text
if L7list.find("true") != -1:
L7Startgood = L7EndGood
L7StartlogT = L7EndLogT
print("L7 good")
else:
print("L7 numbers didn't go through. Will not update starting numbers.")
if (L8SendGood == 0) and (L8ChangeLoss == 0):
print("Zero numbers no Send Line 8")
else:
print("sending L8")
eight = requests.post(url, data=parametersL8,verify=False,timeout=out-time)
#print(eight)
L8list = eight.text
if L8list.find("true") != -1:
L8Startgood = L8EndGood
L8StartlogT = L8EndLogT
print("L8 good")
else:
print("L8 numbers didn't go through. Will not update starting numbers.")
if (L6SendGood == 0) and (L6SendLoss == 0):
print("Zero numbers no Send Line 6") #This is just for my entertainment
else:
print("sending L6")
six = requests.post(url, data=parametersL6,verify=False,timeout=out-time) #line actually making the call to upload the log
#print(six)
L6list = six.text
if L6list.find("true") != -1:
L6Startgood = L6EndGood
L6Startlog = L6EndLog
print("L6 good")
else:
print("Number didn't go through. Will not update starting numbers.")
except Exception as e:
print(e)

Adding a new name/item to a list and calling that variable globally?

I'm pretty much brand new to coding and decided to start with Python. I have been working on a simple "Number Guessing Game" and have evolved it a bit more each iteration.
I decided that I want to make it a little bit more robust that just finishing after the number is guessed.
I want the user/player to enter their name, have that name stored, and then used throughout... until the end, when they're asked if they want to play again and if it's the 'same user?" and if they say, "No.", I want it to append a new name to the list and then go through the game again.
This is what I've got so far... please be gentle... I know there's some errors :(
import sys
import os
import random
global player
while True:
def GuessingGame():
player = []
player.append(input("Please Enter Your Name:\n")),
# player_name = input("Please enter your name: \n")
print(f"Hello, {player[0]}! Let's get started!\n")
number = 500
count = 1
guess = int(input("Guess a number between 1 and 1000: \n"))
while guess != number:
count += 1
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
guess = int(input("Try again...\n"))
if guess == number:
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1 == ("y" or "Y"):
sameplayer = str(input("Is this still {player[0]}? Y1 or N1\n"))
if sameplayer == ("y1" or "Y1"):
GuessingGame()
else:
newplayer = player.extend(str(input("Please Enter New Player's Name:\n")))
print(f"Hello, {player[1]}!, Let's Get Started!")
return
GuessingGame()
Again, this is the first time I'm sharing anything I've done... so please don't just wreck me :)
Here i copy the same code you wrote, but with a little bit of modifications that i felt were needed to be made.
from random import randint
player = None
def GuessingGame():
global player
if player is None:
player = input("Please Enter Your Name:\n")
print(f"Hello, {player}! Let's get started!\n")
number = randint(1, 1000)
guess = int(input("Guess a number between 1 and 1000: \n"))
count = 1
while guess != number:
if guess > (number + 10):
print("TOO HIGH, a little lower...")
elif guess < (number - 10):
print("TOO LOW... guess higher!")
elif guess > (number + 5):
print("You're getting warmer, but still TOO HIGH, a little lower...")
elif guess < (number - 5):
print("You're getting warmer, but still TOO LOW... higher!")
elif guess < number:
print("You're REALLY warm, but still a bit TOO LOW")
elif guess > number:
print("You're REALLY, but still a bit TOO HIGH")
if guess == number:
break
else:
count += 1
guess = int(input("Try again...\n"))
print(f"You got it!!! It took you {count} tries to guess {number}\n")
response1 = str(input("Would you like to try again? Y or N\n"))
if response1.lower() == 'y':
sameplayer = str(input(f"Is this still {player}? Y or N\n"))
if sameplayer.lower() == 'n':
player = None
return
else:
return
while True:
GuessingGame()
Let me know if you got any questions.

find out min and max in python 3

5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
print(num)
print("Maximum", largest)
and the output must be like this
Invalid input
Maximum is 10
Minimum is 2
somebody please help me with this????? enter image description here
I think this will do your work,
With simple if conditions
# Defining two variables to None.
largest = None
smallest = None
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# assign the values of largest and smallest to num if its None ( on first iteration)
if largest is None:
largest = int(num)
if smallest is None:
smallest = int(num)
# changing the values of it greater or smaller
if int(num) > largest:
largest = int(num)
if int(num) < smallest:
smallest = int(num)
# capture the type error and ignores.
except ValueError:
print("ignored.")
continue
print("Maximum: " + str(largest))
print("Minimum: " + str(smallest))
By making use of list and it's methods
# Defining an empty list.
myList = []
# starting an infinite loop
while True:
num = input("Enter a number: ")
# try block to capture ValueError
try:
if num == "done":
break
# append the entered number to list if valid
myList.append(int(num))
# catches value error and ignores it
except ValueError:
print("ignored.")
continue
# prints maximum and min
if len(myList) > 0:
print("Maximum: " + str(max(myList)))
print("Minimum: " + str(min(myList)))
else:
print("List is empty")
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done":
break
num = int(num)
if largest is None or largest < num:
largest = num
elif smallest is None or smallest > num:
smallest = num
except ValueError:
print("Invalid input")
print ("Maximum is", largest)
print ("Minimum is", smallest)
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" :
break
try:
n = int(num)
except:
print ('Invalid input')
continue
if largest is None or n > largest:
largest = n
if smallest is None or n < smallest:
smallest = n
print("Maximum is", largest)
print("Minimum is", smallest)
#Print out largest and smallest number
largest=None
smallest=None
while True:
n = input('Enter a number: ')
if n == "done":
break
try:
num=int(n)
if largest is None:
largest = num
elif num > largest:
largest = num
if smallest is None:
smallest = num
elif num < smallest:
smallest = num
except:
print("Invalid input")
print('maximum:', largest)
print('Minimum:', smallest)

speed up prime number generating

I have written a program that generates prime numbers . It works well but I want to speed it up as it takes quite a while for generating the all the prime numbers till 10000
var list = [2,3]
var limitation = 10000
var flag = true
var tmp = 0
for (var count = 4 ; count <= limitation ; count += 1 ){
while(flag && tmp <= list.count - 1){
if (count % list[tmp] == 0){
flag = false
}else if ( count % list[tmp] != 0 && tmp != list.count - 1 ){
tmp += 1
}else if ( count % list[tmp] != 0 && tmp == list.count - 1 ){
list.append(count)
}
}
flag = true
tmp = 0
}
print(list)
Two simple improvements that will make it fast up through 100,000 and maybe 1,000,000.
All primes except 2 are odd
Start the loop at 5 and increment by 2 each time. This isn't going to speed it up a lot because you are finding the counter example on the first try, but it's still a very typical improvement.
Only search through the square root of the value you are testing
The square root is the point at which a you half the factor space, i.e. any factor less than the square root is paired with a factor above the square root, so you only have to check above or below it. There are far fewer numbers below the square root, so you should check the only the values less than or equal to the square root.
Take 10,000 for example. The square root is 100. For this you only have to look at values less than the square root, which in terms of primes is roughly 25 values instead of over 1000 checks for all primes less than 10,000.
Doing it even faster
Try another method altogether, like a sieve. These methods are much faster but have a higher memory overhead.
In addition to what Nick already explained, you can also easily take advantage of the following property: all primes greater than 3 are congruent to 1 or -1 mod 6.
Because you've already included 2 and 3 in your initial list, you can therefore start with count = 6, test count - 1 and count + 1 and increment by 6 each time.
Below is my first attempt ever at Swift, so pardon the syntax which is probably far from optimal.
var list = [2,3]
var limitation = 10000
var flag = true
var tmp = 0
var max = 0
for(var count = 6 ; count <= limitation ; count += 6) {
for(var d = -1; d <= 1; d += 2) {
max = Int(floor(sqrt(Double(count + d))))
for(flag = true, tmp = 0; flag && list[tmp] <= max; tmp++) {
if((count + d) % list[tmp] == 0) {
flag = false
}
}
if(flag) {
list.append(count + d)
}
}
}
print(list)
I've tested the above code on iswift.org/playground with limitation = 10,000, 100,000 and 1,000,000.