This question already has answers here:
How is returning the output of a function different from printing it? [duplicate]
(9 answers)
Closed 2 months ago.
The challenge is to square an input number.
import sys
# import numpy as np
# import pandas as pd
# from sklearn import ...
def square(x):
return print(x ** 2)
for line in sys.stdin:
print(line, end="")
I don't know how to use sys.stdin I guess because I don't know how to pass through the challenge test inputs for x.
Apologies, but I can't find any answers.
If you want to read lines from standard input, you can use input. It will raise EOFError at end of file. To read lines successively and handle them you can just read in a loop with an exception handler for EOFError.
try:
while True:
line = input()
x = int(line)
print(square(x))
except EOFError:
pass
Or for fun, wrap this up in a function that yields out the lines.
def read_stdin():
try:
while True:
yield input()
except EOFError:
pass
for line in read_stdin():
print(square(int(line)))
Related
This question already has answers here:
How can I get new results from randint while in a loop?
(2 answers)
Closed 3 years ago.
I am able to generate random hex values in a specific range using the code below, but I get the same random value on each line if i set my counter to more than 1. I'm guessing I need a loop, I have tried with "for x in range" but my implementation must be wrong as it overflows. I'm new to python and have searched for days but can't seem to find how to implement it correctly.
import random
import sys
#ran = random.randrange(2**64)
ran = random.randrange(0x8000000000000000, 0xFFFFFFFFFFFFFFFF)
myhex = "%064x" % ran
#limit string to 64 characters
myhex = myhex[:64]
counter = 0
file = open('output.txt', 'w')
sys.stdout = file
for result in myhex:
print(myhex)
counter += 1
if counter > 10:
break
As pointed out in the comments, you're generating the random number only once. To have a new random value for each iteration, you need to put the generation code in the loop as follows:
# ... your imports
with open('output.txt', 'w') as f:
for _ in range(10):
ran = random.randrange(0x8000000000000000, 0xFFFFFFFFFFFFFFFF)
myhex = "%064x" % ran
#limit string to 64 characters
myhex = myhex[:64]
f.write(myhex)
f.write("\n")
Also, if you want to dump the results in a file, a better approach is to write directly to the file without changing sys.stdout, as done in the above code.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I've done this before but i think this error is showing up because I'm not looping the code, the code works only once then on the second attempt is shows an error.
My Code:
import string
import time
def timer(x):
for n in range(x,0,-1):
time.sleep(1)
print(n)
print("Times Up"+"\n")
ask("Time for: ")
def ask(a):
x=int(input(str(a)))
print("\n"+"Clock's Ticking")
timer(x)
try:
ask("Time for: ")
except ValueError:
ask("Enter a number to time: ")
I want my code to not error when i put in something that isnt a integer for the time but dont know how to loop the exception code until the user enters a integer.
Move the exception handling to ask function:
import string
import time
def timer(x):
for n in range(x,0,-1):
time.sleep(1)
print(n)
print("Times Up"+"\n")
ask("Time for: ")
def ask(a):
x = None
while x is None:
try:
x=int(input(str(a)))
except ValueError:
print('Enter a number to time!')
timer(x)
ask("Time for: ")
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 6 years ago.
Just a little project i'm working on to improve my knowledge.
Curious as to why the program always returns failure, even if the captcha is correctly entered. I assume it has something to do with the results not being stored in memory?
import string
import random
def captcha_gen(size=7, chars=string.ascii_letters + string.digits):
return ''.join(random.SystemRandom().choice(chars) for _ in range(size))
results = print(captcha_gen())
user_input = input("Please enter the captcha code as you see it: ")
if user_input == results:
print("success")
elif user_input != results:
print("failure")
else:
print("error")
Thanks!
results = print(captcha_gen())
print() returns None - it is used to print stuff to the screen. In this case, it is grabbing the output of captcha_gen() and printing it to the screen.
All functions in Python return something - if they don't specify what they return, then it is an implicit None
You want
results = captcha_gen()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok I'm learning read and write files at the moment but I need a little help to sum the numbers in a file.
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
for i in range (the range of int is unknown)
file = sample.read ()
sample.close ()
main ()
You may iterate over the file like this:
for i in sample:
and convert using int() to an integer.
The for loop can be done with map and the sum with sum.
This is the final code:
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
result = sum(map(int, sample))
print(result)
sample.close ()
main ()
What you want is:
for line in sample:
# process the line
If each line just contains an integer, you can simplify it further to sum(map(int, sample)).
To add safety, you should cast your integers with error checking and ensure that the file exists before reading it.
import os
def safecast(newtype, val, default=None):
try:
return newtype(val)
except ValueError:
pass
return default
def sumfile(filename):
if not os.path.isfile(filename):
return None
sum = 0
with open(filename, "r") as file:
for line in file:
sum += safecast(int, line, 0)
return sum
sum = sumfile(r'C:\user\desktop\text.txt')
print(sum)
This question already has answers here:
Length of generator output [duplicate]
(9 answers)
How to look ahead one element (peek) in a Python generator?
(18 answers)
How to print a generator expression?
(8 answers)
Closed 8 years ago.
Yesterday I have been implementing a small Python scripts that checks difference between two files (using difflib), printing the result if there is any, exiting with code 0 otherwise.
The precise method, difflib.unified_diff() is returning a generator on the diffs found. How can I test this generator to see if it needs to be printed? I tried using len(), sum() to see what was the size of this generator but then it is impossible to print it.
Sorry to ask such a silly question but I really don't see what is the good practice on that topic.
So far this is what I am doing
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
if (len(list(diff))):
print("Differences found!")
# Recomputing the generator again: how stupid is that!
diff = difflib.unified_diff(fromlines, tolines, n=0)
sys.stdout.writelines(diff)
else:
print("OK!")
You're already converting your generator to a list, so you don't need to rebuild it.
diff = list(difflib.unified_diff(fromlines, tolines, n=0))
if diff:
...
sys.stdout.writelines(diff)
else:
...
You don't even need to convert the generator to a list if you don't want by using a simple flag:
diff = difflib.unified_diff(fromlines, tolines, n=0)
f = False
for line in diff:
if not f:
print("Differences found!")
f = True
sys.stdout.write(line)
if not f:
print("OK!")
You could convert the generator into a list.
diff = list(difflib.unified_diff(fromlines, tolines, n=0))
I think you can't, and the proper way is probably to generate all data until you raise StopIteration and then get the length of what you have generated.
What's wrong with :
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
difflines = list(diff)
if len(difflines) :
sys.stdout.writelines(difflines)
else:
print("OK!")